In this article, we have three tasks:
- Create SQL Table
- Create Flutter Screen
- Create PHP Api
Part 1: Create SQL Table
You can create a table named contact
with the specified fields using the following SQL code:
CREATE TABLE contact (
id INT AUTO_INCREMENT PRIMARY KEY,
con_name TEXT,
con_mobile TEXT,
con_email TEXT,
con_message LONGTEXT
);
This SQL code creates a table with the following columns:
id
: An auto-incremented primary key field of integer type.con_name
: A text field for contact names.con_mobile
: A text field for contact mobile numbers.con_email
: A text field for contact email addresses.con_message
: A long text field for contact messages or comments.
You can execute this SQL code in your database management system to create the contact
table with the specified structure.
Part 2: Create a Flutter Screen
Let’s break down the Flutter screen for a contact form step by step:
- Import Statements:
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
The code starts by importing the necessary Flutter and HTTP packages.
- Widget Class:
class Contact extends StatefulWidget {
const Contact({Key? key}) : super(key: key);
@override
_ContactState createState() => _ContactState();
}
This is a typical Flutter widget class that represents the contact form. It extends StatefulWidget
and has a state class associated with it.
- State Class:
class _ContactState extends State<Contact> {
Here, the state class _ContactState
is defined, which contains the logic and content of the contact form.
- Text Editing Controllers:
final TextEditingController nameController = TextEditingController();
final TextEditingController mobileController = TextEditingController();
final TextEditingController emailController = TextEditingController();
final TextEditingController messageController = TextEditingController();
Four text editing controllers are created to manage the input data for name, mobile, email, and message fields.
submitForm
Method:
Future<void> submitForm() async {
// ...
}
The submitForm
method is defined as an asynchronous function. This method will handle the submission of the contact form data to the server via HTTP.
- Scaffold Widget:
return Scaffold(
appBar: AppBar(
title: Text('Contact Us'),
backgroundColor: Colors.pink,
),
body: SingleChildScrollView(
child: Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
children: [
// Form fields go here
],
),
),
),
);
The Scaffold
widget is used to create the basic structure of the screen. It includes an app bar with the title “Contact Us.” The main content is placed inside a SingleChildScrollView
to allow scrolling if the content overflows.
- Form Fields:
TextFormField(
controller: nameController,
decoration: InputDecoration(
labelText: 'Name',
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(10),
),
),
),
A TextFormField
widget is used for each form field (Name, Mobile, Email, and Message). It includes a controller for managing the input, a label, and a border for styling.
- The Name field accepts the user’s name.
- The Mobile field accepts a 10-digit mobile number with a number keyboard.
- The Email field accepts an email address with the email keyboard.
- The Message field is a multi-line text input for the user’s message.
- Submit Button:
ElevatedButton(
onPressed: submitForm,
child: Text('Submit'),
),
An ElevatedButton
is provided for submitting the form. When clicked, it triggers the submitForm
method.
Overall, this Flutter screen creates a contact form with text input fields for the user’s name, mobile number, email address, and message. Upon clicking the “Submit” button, the form data is sent to the specified API endpoint using the HTTP POST method. Any response from the server is logged for further handling.
Full Source Code
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
class Contact extends StatefulWidget {
const Contact({Key? key}) : super(key: key);
@override
_ContactState createState() => _ContactState();
}
class _ContactState extends State<Contact> {
final TextEditingController nameController = TextEditingController();
final TextEditingController mobileController = TextEditingController();
final TextEditingController emailController = TextEditingController();
final TextEditingController messageController = TextEditingController();
Future<void> submitForm() async {
final url = Uri.parse('https://booppers.tk/api/contact.php');
final response = await http.post(
url,
body: {
'con_name': nameController.text,
'con_mobile': mobileController.text,
'con_email': emailController.text,
'con_message': messageController.text,
},
);
if (response.statusCode == 200) {
// Form submitted successfully. You can handle the response here.
print('Response: ${response.body}');
} else {
// Form submission failed. Handle the error.
print('Error: ${response.reasonPhrase}');
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Contact Us'),
backgroundColor: Colors.pink,
),
body: SingleChildScrollView(
child: Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
children: [
TextFormField(
controller: nameController,
decoration: InputDecoration(
labelText: 'Name',
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(10),
),
),
),
SizedBox(height: 10),
TextFormField(
controller: mobileController,
decoration: InputDecoration(
labelText: 'Mobile (10 digits)',
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(10),
),
),
keyboardType: TextInputType.number,
),
SizedBox(height: 10),
TextFormField(
controller: emailController,
decoration: InputDecoration(
labelText: 'Email',
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(10),
),
),
keyboardType: TextInputType.emailAddress,
),
SizedBox(height: 10),
TextFormField(
controller: messageController,
decoration: InputDecoration(
labelText: 'Message',
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(10),
),
),
maxLines: 5,
),
SizedBox(height: 20),
ElevatedButton(
onPressed: submitForm,
child: Text('Submit'),
),
],
),
),
),
);
}
}
Part 3: Create PHP API
Let’s break down the PHP code for handling a contact form submission step by step:
- Include Statements:
include('cors.php'); // Include CORS headers if needed
include('../database.php'); // Include your database connection
The code starts by including necessary files, including CORS headers and the database connection file.
- Header for JSON Response:
header('Content-Type: application/json');
This sets the response content type as JSON, indicating that the server will respond with JSON data.
- Initialize Response Array:
$response = array();
An empty associative array, $response
, is initialized to store the response data.
- Try-Catch Block for Error Handling:
try {
// Code for handling the request and database interaction goes here
} catch (Exception $e) {
$response['success'] = false;
$response['message'] = $e->getMessage();
}
The code is wrapped in a try-catch block to handle exceptions. If an error occurs at any point, it’s caught and an error response is generated.
- Request Method Check:
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// ...
} else {
throw new Exception("Invalid request method.");
}
This part checks if the request method is POST. It ensures that the code only proceeds if the request is a POST request. If it’s not, an exception is thrown.
- Data Validation:
if (empty($con_name) || empty($con_mobile) || empty($con_email) || empty($con_message)) {
throw new Exception("All fields are required.");
}
Input data validation is performed to ensure that all required fields (Name, Mobile, Email, and Message) are not empty. If any field is empty, an exception is thrown to handle this error.
You can add more validation for mobile number and email format if needed to ensure data integrity.
- Database Query:
$sql = "INSERT INTO contact (con_name, con_mobile, con_email, con_message) VALUES (:con_name, :con_mobile, :con_email, :con_message)";
$stmt = $conn->prepare($sql);
A SQL query is prepared to insert the contact data into the database table “contact.” A prepared statement is used for security and efficiency.
- Binding Parameters:
$stmt->bindParam(':con_name', $con_name);
$stmt->bindParam(':con_mobile', $con_mobile);
$stmt->bindParam(':con_email', $con_email);
$stmt->bindParam(':con_message', $con_message);
The parameters are bound to the prepared statement to securely insert the data.
- Database Execution and Response:
if ($stmt->execute()) {
$response['success'] = true;
$response['message'] = "Data inserted successfully.";
} else {
throw new Exception("Database query failed: " . $stmt->errorInfo());
}
The query is executed. If the execution is successful, a success response is generated. If there’s an issue with the database query, an exception is thrown, and the error message is included in the response.
- Error Handling:
} catch (Exception $e) { $response['success'] = false; $response['message'] = $e->getMessage(); }
If any errors occur during the process, they are caught, and the response is set to indicate failure with an error message. - JSON Response:
echo json_encode($response);
Finally, the response data, whether it’s a success message or an error message, is encoded as JSON and sent as the HTTP response. This allows the client-side application to handle the response appropriately.
Full Source Code:
<?php
include('cors.php'); // Include CORS headers if needed
include('../database.php'); // Include your database connection
header('Content-Type: application/json');
// Initialize an empty response array.
$response = array();
try {
// Check if the request is a POST request.
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// Get data from the POST request.
$con_name = $_POST['con_name'];
$con_mobile = $_POST['con_mobile'];
$con_email = $_POST['con_email'];
$con_message = $_POST['con_message'];
// Validate input data
if (empty($con_name) || empty($con_mobile) || empty($con_email) || empty($con_message)) {
throw new Exception("All fields are required.");
}
// Add more validation for mobile number and email format if needed
// Create a SQL query to insert the contact data into your database.
$sql = "INSERT INTO contact (con_name, con_mobile, con_email, con_message) VALUES (:con_name, :con_mobile, :con_email, :con_message)";
$stmt = $conn->prepare($sql);
// Bind the parameters.
$stmt->bindParam(':con_name', $con_name);
$stmt->bindParam(':con_mobile', $con_mobile);
$stmt->bindParam(':con_email', $con_email);
$stmt->bindParam(':con_message', $con_message);
if ($stmt->execute()) {
$response['success'] = true;
$response['message'] = "Data inserted successfully.";
} else {
throw new Exception("Database query failed: " . $stmt->errorInfo());
}
} else {
throw new Exception("Invalid request method.");
}
} catch (Exception $e) {
$response['success'] = false;
$response['message'] = $e->getMessage();
}
// Output the response as JSON.
echo json_encode($response);
?>
Very Nice Article on Flutter PHP API.