Insert data in MySql Database with Dio Library API

 import "package:flutter/material.dart";

import "package:dio/dio.dart";

void main() {
runApp(const MyApp());
}

class MyApp extends StatelessWidget {
const MyApp({super.key});

@override
Widget build(BuildContext context) {
return MaterialApp(
title: "Insert data with Dio",
debugShowCheckedModeBanner: false,
theme: ThemeData(
appBarTheme: const AppBarTheme(
backgroundColor: Colors.grey,
centerTitle: true,
),
),
home: const InsertDataDio(),
);
}
}

class InsertDataDio extends StatefulWidget {
const InsertDataDio({super.key});

@override
State<InsertDataDio> createState() {
return InsertDataDioState();
}
}

class InsertDataDioState extends State<InsertDataDio> {
TextEditingController nameController = TextEditingController();
TextEditingController birthDateController = TextEditingController();
TextEditingController phoneController = TextEditingController();
TextEditingController genderController = TextEditingController();

Future<void> _insert() async {
String name = nameController.text.trim();
String birth_date = birthDateController.text.trim();
String phone = phoneController.text.trim();
String gender = genderController.text.trim();

/// Your server endpoint URL
String url = "http://192.168.1.35/Flutter/insert.php";

try {
/// Form data to send
FormData formData = FormData.fromMap(
{
"name": name,
"birth_date": birth_date,
"phone": phone,
"gender": gender,
},
);

/// Send POST Request
Response response = await Dio().post(url, data: formData);

/// Handle response
print("Response status : ${response.statusCode}");
print("Response data : ${response.data}");

/// You can handle success or failure based on the response here
} catch (error) {
print("Error sending data : $error");
}
}

@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: () {
return FocusManager.instance.primaryFocus?.unfocus();
},
child: Scaffold(
appBar: AppBar(
title: const Text(
"Insert Data with Dio Library",
style: TextStyle(fontWeight: FontWeight.bold),
),
),
body: Center(
child: SizedBox(
width: 300.0,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
TextFormField(
controller: nameController,
decoration: const InputDecoration(
hintText: "Enter the Name",
border: OutlineInputBorder(),
),
),
const SizedBox(height: 30.0),
TextFormField(
controller: birthDateController,
decoration: const InputDecoration(
hintText: "Enter the birthdate",
border: OutlineInputBorder(),
),
),
const SizedBox(height: 30.0),
TextFormField(
controller: phoneController,
keyboardType: TextInputType.phone,
maxLength: 10,
decoration: const InputDecoration(
hintText: "Enter the phone number",
border: OutlineInputBorder(),
),
),
const SizedBox(height: 30.0),
TextFormField(
controller: genderController,
decoration: const InputDecoration(
hintText: "Enter the gender",
border: OutlineInputBorder(),
),
),
const SizedBox(height: 50.0),
ElevatedButton(
onPressed: () {
_insert();
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text("Data inserted Successfully..."),
duration: Duration(seconds: 2),
),
);
nameController.clear();
birthDateController.clear();
phoneController.clear();
genderController.clear();
},
style: ElevatedButton.styleFrom(
backgroundColor: Colors.blue,
fixedSize: const Size(300.0, 50.0),
),
child: const Text(
"Insert",
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 20.0,
color: Colors.white),
),
),
],
),
),
),
),
);
}
}
<?php

header('Access-Control-Allow-Origin: *');

header('Access-Control-Allow-Methods: GET, POST');

header("Access-Control-Allow-Headers: X-Requested-With");

        $name=$_REQUEST["name"];
        $birth_date=$_REQUEST["birth_date"];
        $phone=$_REQUEST["phone"];
        $gender = $_REQUEST["gender"];
       
         $con = new mysqli("localhost","root","","student");
      $result= $con->query("insert into personal(name,birth_date,phone,gender) values('$name','$birth_date','$phone','$gender')");
     
      if($result)
      {
        $result= $con->query("select * from personal");    
          while($r= $result->fetch_object())
          {
            $row['personal'][]=$r;
          }
           echo json_encode($row);
      }
?>



Comments

Popular posts from this blog

Pagination with Bloc Pattern in Flutter

Pagination First Practical in Flutter

ExpansionPanel with ExpansionPanelList with Complete Collapse Operation in Flutter