Insert Data in Mysql Database with HTTP Library with Insert API

 import "package:flutter/material.dart";

import "package:http/http.dart" as http;

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

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

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

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

@override
State<InsertData> createState() {
return InsertDataState();
}
}

class InsertDataState extends State<InsertData> {
TextEditingController nameController = TextEditingController();
TextEditingController birthDateController = TextEditingController();
TextEditingController phoneController = TextEditingController();
TextEditingController genderController = TextEditingController();

Future<void> insertData() async {
const String url = "http://192.168.1.36/Flutter/insert.php";
final Map<String, dynamic> data = {
"name": nameController.text,
"birth_date": birthDateController.text,
"phone": phoneController.text,
"gender": genderController.text,
};

try {
final response = await http.post(
Uri.parse(url),
body: data,
);

if (response.statusCode == 200) {
print("Data inserted Successfully");
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text("Data inserted Successfully..."),
duration: Duration(seconds: 2),
),
);
} else {
print("Error : ${response.statusCode}");
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text("Oops ! Operation Failed. Data not inserted..."),
duration: Duration(seconds: 2),
),
);
}
} catch (e) {
print("Error : $e");
}
}

@override
void dispose() {
super.dispose();
nameController.dispose();
birthDateController.dispose();
phoneController.dispose();
genderController.dispose();
}

@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: () {
return FocusManager.instance.primaryFocus?.unfocus();
},
child: Scaffold(
appBar: AppBar(
title: const Text(
"Insert Data with HTTP Library API",
style: TextStyle(fontWeight: FontWeight.bold),
),
),
body: Center(
child: SizedBox(
width: 350.0,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
TextFormField(
controller: nameController,
decoration: InputDecoration(
hintText: "Enter the name",
labelText: "Name",
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(11.0),
),
),
),
const SizedBox(height: 20.0),
TextFormField(
controller: birthDateController,
decoration: InputDecoration(
hintText: "Enter the birth date",
labelText: "Birth date",
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(11.0),
),
),
),
const SizedBox(height: 20.0),
TextFormField(
controller: phoneController,
keyboardType: TextInputType.phone,
maxLength: 10,
decoration: InputDecoration(
hintText: "Enter the phone Number",
labelText: "Phone",
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(11.0),
),
),
),
const SizedBox(height: 20.0),
TextFormField(
controller: genderController,
decoration: InputDecoration(
hintText: "Enter the gender",
labelText: "gender",
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(11.0),
),
),
),
const SizedBox(height: 50.0),
ElevatedButton(
onPressed: () {
insertData();
// 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 Data",
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

ExpansionPanel with ExpansionPanelList with Complete Collapse Operation in Flutter

Pagination with Bloc Pattern in Flutter

Pagination First Practical in Flutter