Flutter #103: MySQL + DataTable, SQL CRUD Operations with REST API


Flutter #103: MySQL + DataTable, SQL CRUD Operations with REST API

MySQL + DataTable, SQL CRUD Operations with REST API. Copy and paste the below code as per your requirements.

db.php

<?php
$db = mysqli_connect('localhost','root','','userdata');
if(!$db)
{
	echo "Database connection failed";
}
?>

create.php

<?php
header('Content-Type: application/json');
include('db.php');
if(!isset($_POST['title']) && !isset($_POST['content'])) {
        echo json_encode("No Data Sent");
    }      
else{
    $title = $_POST['title'];
    $content = $_POST['content'];
    $result = mysqli_query($db,"INSERT INTO blog (title, content) VALUES ('{$title}','{$content}')");
    if($result)
    {
        echo json_encode("Success");
    }
    else{
        echo json_encode("Failed");
    }
}
?>

list.php

<?php
header('Content-Type: application/json');
include('db.php');
	$result = mysqli_query($db,"SELECT * FROM blog");
	if($result)
	{
	    $rows = array();
		while($r = mysqli_fetch_assoc($result))
		{
			$rows[] = $r;
		}
		print json_encode($rows);

	}
	?>

update.php

<?php
header('Content-Type: application/json');
include('db.php');
if(!isset($_POST['id']) && !isset($_POST['title']) && !isset($_POST['content'])) {
        echo json_encode("No Data Sent");
    }      
else{
    $id = $_POST['id'];
    $title = $_POST['title'];
    $content = $_POST['content'];
    $result = mysqli_query($db,"UPDATE blog SET title = '{$title}', content = '{$content}' WHERE id ={$id}");
    if($result)
    {
        echo json_encode("Success");
    }
    else{
        echo json_encode("Failed");
    }
}
?>

delete.php

<?php
header('Content-Type: application/json');
include('db.php');
if(!isset($_POST['id'])) {
        echo json_encode("No Data Sent");
    }      
else{
    $id = $_POST['id'];
    $result = mysqli_query($db,"DELETE FROM blog WHERE id = {$id}");
    if($result)
    {
        echo json_encode("Success");
    }
    else{
        echo json_encode("Failed");
    }
}
?>

pubspec.yaml

http: ^0.13.4 #to interact with api
fluttertoast: ^8.0.9 #to display toast message

main.dart

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'dart:async';
import 'dart:convert';
import 'package:http/http.dart' as http;
import 'details.dart';
import 'newdata.dart';
void main()=>runApp(MaterialApp(
  title: "Api Test",
  debugShowCheckedModeBanner: false,
  theme: ThemeData(
    primarySwatch: Colors.indigo,
  ),
  home: const Home(),
));
class Home extends StatefulWidget {
  const Home({Key? key}) : super(key: key);
  @override
  _HomeState createState() => _HomeState();
}
class _HomeState extends State<Home> {
  Future<List> getData() async{
    var url = Uri.parse('http://192.168.0.104/example/list.php'); //Api Link
    final response = await http.post(url);
    return jsonDecode(response.body);
  }
  @override
  void initState() {
    getData();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar (
        title: const Center(child: Text("PHP MySQL CRUD"),),
        shape: const BeveledRectangleBorder(
            borderRadius: BorderRadius.only(bottomLeft: Radius.circular(20),bottomRight: Radius.circular(20))
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: ()=>Navigator.of(context).push(
          MaterialPageRoute(
            builder: (BuildContext contex)=> NewData(),
          ),
        ),
        child: const Icon(Icons.add),
      ),
      body:FutureBuilder<List>(
        future: getData(),
        builder: (ctx,ss) {
          if(ss.hasError){
            print("error");
          }
          if(ss.hasData){
            return Items(list:ss.data!);
          }
          else{
            return const CircularProgressIndicator();
          }
        },
      ),
    );
  }
}

class Items extends StatelessWidget {
  List list;
  Items({Key? key, required this.list}) : super(key: key);
  @override
  Widget build(BuildContext context) {
    return ListView.builder(
       itemCount: list==null?0:list.length,
      itemBuilder: (ctx,i){
        return ListTile(
          leading: const Icon(Icons.text_snippet_outlined),
          title: Text(list[i]['title']), //Key
          subtitle: Text(list[i]['content']), //Key
          onTap: ()=>Navigator.of(context).push(MaterialPageRoute(builder: (BuildContext context)=>Details(list:list,index:i),
          )),
        );
      }
    );
  }
}

newdata.dart

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:example/main.dart';
import 'package:http/http.dart' as http;
class NewData extends StatefulWidget {
  const NewData({Key? key}) : super(key: key);
  @override
  _NewDataState createState() => _NewDataState();
}
class _NewDataState extends State<NewData> {

  TextEditingController title = TextEditingController();
  TextEditingController content = TextEditingController();
  void addData(){
    var url = Uri.parse('http://192.168.0.104/example/create.php'); //Inserting Api Calling
    http.post(url, body: {"title": title.text,
    "content": content.text}); // parameter passed
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar (
        title: const Center(child: Text("Add New Blog"),),
        shape: const BeveledRectangleBorder(
            borderRadius: BorderRadius.only(bottomLeft: Radius.circular(20),bottomRight: Radius.circular(20))
        ),
      ),
      body: ListView(
        children: [
          Container(
            padding: const EdgeInsets.all(10),
            child: TextFormField(
              controller: title,
              autofocus: true,
              decoration: const InputDecoration(
                border: OutlineInputBorder(),
                labelText: 'Enter Title',
                hintText: 'Enter Title',
                prefixIcon: IconButton(
                  onPressed: null,
                  icon: Icon(Icons.title),
                ),
              ),
            ),
          ),
          Container(
            padding: const EdgeInsets.all(10),
            child: TextFormField(
              maxLines: 5,
              controller: content,
              autofocus: true,
              decoration: const InputDecoration(
                border: OutlineInputBorder(),
                labelText: 'Enter Content',
                hintText: 'Enter Content',
                prefixIcon: IconButton(
                  onPressed: null,
                  icon: Icon(Icons.text_snippet_outlined),
                ),
              ),
            ),
          ),
          Container(
            padding: const EdgeInsets.all(10),
            child: MaterialButton(
              child: const Text("Add Data"),
              color:  Colors.amber,
              onPressed: (){
                addData();
                Navigator.of(context).push(
                  MaterialPageRoute(builder: (BuildContext context)=>const Home()),
                );
              },
            ),
          ),
        ],
      ),
    );
  }
}

editdata.dart

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:example/main.dart';
import 'package:http/http.dart' as http;
class Edit extends StatefulWidget {
  final List list;
  final int index;
  Edit({Key? key, required this.list, required this.index}) : super(key: key);
  @override
  _EditState createState() => _EditState();
}

class _EditState extends State<Edit> {
  late TextEditingController title;
  late TextEditingController content;


  void editData(){
    var url = Uri.parse('http://192.168.0.104/example/update.php'); //update api calling
    http.post(url, body: {'id':widget.list[widget.index]['id'],
    'title': title.text,
    'content':content.text});
  }
  @override
  void initState() {
    title = TextEditingController(text: widget.list[widget.index]['title']); //setting up the existing values in textediting control
    content = TextEditingController(text: widget.list[widget.index]['content']);
    super.initState();
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar:  AppBar (
        title: Center(child: Text("Edit Data ${widget.list[widget.index]['title']}"),),
        shape: const BeveledRectangleBorder(
            borderRadius: BorderRadius.only(bottomLeft: Radius.circular(20),bottomRight: Radius.circular(20))
        ),
      ),
      body: ListView(
        children: [
          Container(
            padding: const EdgeInsets.all(10),
            child: TextFormField(
              controller: title,
              autofocus: true,
              decoration: const InputDecoration(
                border: OutlineInputBorder(),
                labelText: 'Enter Title',
                hintText: 'Enter Title',
                prefixIcon: IconButton(
                  onPressed: null,
                  icon: Icon(Icons.title),
                ),
              ),
            ),
          ),
          Container(
            padding: const EdgeInsets.all(10),
            child: TextFormField(
              maxLines: 5,
              controller: content,
              autofocus: true,
              decoration: const InputDecoration(
                border: OutlineInputBorder(),
                labelText: 'Enter Content',
                hintText: 'Enter Content',
                prefixIcon: IconButton(
                  onPressed: null,
                  icon: Icon(Icons.text_snippet_outlined),
                ),
              ),
            ),
          ),
          Container(
            padding: const EdgeInsets.all(10),
            child: MaterialButton(
              child: const Text("Edit Data"),
              color:  Colors.amber,
              onPressed: (){
                editData();
                Navigator.of(context).push(
                  MaterialPageRoute(builder: (BuildContext context)=>const Home()),
                );
              },
            ),
          ),
        ],
      ),
    );
  }
}

details.dart

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:example/editdata.dart';
import 'package:example/main.dart';

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

class Details extends StatefulWidget {
  List list;
  int index;

  Details({required this.list, required this.index});

  @override
  _DetailsState createState() => _DetailsState();
}

class _DetailsState extends State<Details> {
  void delete() {
    var url = Uri.parse('http://192.168.0.104/example/delete.php'); //deletion api
    http.post(url, body: {'id': widget.list[widget.index]['id']});
  }

  void confirm() {
    AlertDialog alertDialog = AlertDialog(
      content: const Text("Are You Sure?"), //confirming the deletion of record
      actions: [
        MaterialButton(
          child: const Text("YES DELETE"),
          onPressed: () {
            delete();
            Navigator.of(context).push(
                MaterialPageRoute(builder: (BuildContext context) => Home()));
          },
        ),
        MaterialButton(
          child: const Text("NO.."),
          onPressed: () {},
        ),
      ],
    );
    showDialog(builder: (context) => alertDialog, context: context);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar (
        title: Center(child: Text('${widget.list[widget.index]['title']}')),
        shape: const BeveledRectangleBorder(
            borderRadius: BorderRadius.only(bottomLeft: Radius.circular(20),bottomRight: Radius.circular(20))
        ),
      ),
      body: Center(child: Column(
        children: [
          const SizedBox(height: 20,),
          Text(
            widget.list[widget.index]['title'],
            style: const TextStyle(fontSize: 20.0),
          ),
          const SizedBox(height: 20,),
          Text(
            widget.list[widget.index]['content'],
          ),
          const SizedBox(height: 100,),
          Row(children: [
            Container(
                padding: const EdgeInsets.all(10),
                child: MaterialButton(
                  child: const Text("Edit Data"),
                  color:  Colors.amber,
                  onPressed: () => Navigator.of(context).push(
                    MaterialPageRoute(
                        builder: (BuildContext context) =>
                            Edit(list: widget.list, index: widget.index)),
                  ),
                )
            ),
            Container(
                padding: const EdgeInsets.all(10),
                child: MaterialButton(
                    child: const Text("Delete"),
                    color:  Colors.amber,
                    onPressed: (){confirm();}
                )
            ),
          ],)
        ],
      ),)
    );
  }
}

Leave a Reply

Your email address will not be published.