TEXT: FLUTTER: LOGIN TO MYSQL DATABASE THRU API (PHP)

 Here are the codes used in the discussion:

For the back end (API)

<?php
  header('Content-Type: application/json');
  header("Access-Control-Allow-Origin: *");

  include "connection-pdo.php";

  $username = $_GET['username'];
  $password = $_GET['password'];

  $sql = "SELECT * FROM tblusers WHERE usr_username = :username ";
  $sql .= "AND usr_password = :password ";
  $stmt = $conn->prepare($sql);
  $stmt->bindParam(":username", $username);
  $stmt->bindParam(":password", $password);
  $stmt->execute();
  $returnValue = $stmt->fetchAll(PDO::FETCH_ASSOC);
 
  echo json_encode($returnValue);
?>


Front end (Flutter code)


import 'dart:convert';

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});

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
        useMaterial3: true,
      ),
      home: const MyHomePage(title: 'Sample API'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  String _msg = "";
  TextEditingController _usernameController = TextEditingController();
  TextEditingController _passwordController = TextEditingController();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
          child: Padding(
        padding: const EdgeInsets.all(20.0),
        child: Column(
          children: [
            const SizedBox(
              height: 30.0,
            ),
            const Text(
              "Login",
              style: TextStyle(fontSize: 20.0),
            ),
            TextField(
              controller: _usernameController,
              decoration: const InputDecoration(
                  labelText: "Username", hintText: "Enter Username"),
            ),
            const SizedBox(
              height: 30.0,
            ),
            TextField(
              controller: _passwordController,
              obscureText: true,
              decoration: const InputDecoration(
                  labelText: "Password", hintText: "Enter Password"),
            ),
            const SizedBox(
              height: 30.0,
            ),
            ElevatedButton(
              onPressed: () {
                login();
              },
              child: const Text(
                "Login",
              ),
            ),
            const SizedBox(
              height: 30.0,
            ),
            Text(
              _msg,
              style: const TextStyle(fontSize: 20.0),
            ),
          ],
        ),
      )),
    );
  }

  void login() async {
    String url = "http://localhost/flutter/api/login.php";

    final Map<String, dynamic> queryParams = {
      "username": _usernameController.text,
      "password": _passwordController.text
    };

    try {
      http.Response response =
          await http.get(Uri.parse(url).replace(queryParameters: queryParams));

      if (response.statusCode == 200) {
        var user = jsonDecode(response.body); //return type list<Map>
        if (user.isNotEmpty) {
          setState(() {
            _msg = user[0]['usr_fullname'];
          });
        } else {
          setState(() {
            _msg = "Invalid Username or password.";
          });
        }
      } else {
        setState(() {
          _msg = "${response.statusCode} ${response.reasonPhrase}";
        });
      }
    } catch (error) {
      setState(() {
        _msg = "$error";
      });
    }
  }
}





No comments:

Post a Comment

IMAGE: CODE SPLITTING - USE COMPONENTS (NEXT JS)

 CONTACTS LIST (MAIN) contacts_list.js TEXT VERSION view.js update.js TEXT VERSION