BACK END
users.php
<?php
header('Content-Type: application/json');
header("Access-Control-Allow-Origin: *");
class User {
// login
function login($json){
include "connection-pdo.php";
$json = json_decode($json, true);
$sql = "SELECT * FROM tblusers WHERE usr_username = :username ";
$sql .= "AND usr_password = :password ";
$stmt = $conn->prepare($sql);
$stmt->bindParam(":username", $json['username']);
$stmt->bindParam(":password", $json['password']);
$stmt->execute();
$returnValue = $stmt->fetchAll(PDO::FETCH_ASSOC);
unset($conn); unset($stmt);
return json_encode($returnValue);
}
//register
function register($json){
include "connection-pdo.php";
$json = json_decode($json, true);
$sql = "INSERT INTO tblusers(usr_username, usr_password, usr_fullname) ";
$sql .= "VALUES (:username, :password, :fullname) ";
$stmt = $conn->prepare($sql);
$stmt->bindParam(":username", $json['username']);
$stmt->bindParam(":password", $json['password']);
$stmt->bindParam(":fullname", $json['fullname']);
$stmt->execute();
$returnValue = $stmt->rowCount() > 0 ? 1 : 0;
unset($conn); unset($stmt);
return json_encode($returnValue);
}
}
//submitted by the client - operation and json
if ($_SERVER['REQUEST_METHOD'] == 'GET'){
$operation = $_GET['operation'];
$json = $_GET['json'];
}else if($_SERVER['REQUEST_METHOD'] == 'POST'){
$operation = $_POST['operation'];
$json = $_POST['json'];
}
$user = new User();
switch($operation){
case "login":
echo $user->login($json);
break;
case "register":
echo $user->register($json);
break;
case "getUsers":
echo $user->getUsers($json);
break;
}
?>
conection-pdo.php
<?php
$servername = "localhost";
$dbusername = "root";
$dbpassword = "";
$dbname = "dbcontacts";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $dbusername, $dbpassword);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//echo "Connected successfully";
} catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
?>
FRONT END
main.dart (LOGIN PAGE)
import 'dart:convert';
import 'package:db/contacts_list.dart';
import 'package:db/register.dart';
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 = "";
final TextEditingController _usernameController = TextEditingController();
final 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),
),
const SizedBox(
height: 30.0,
),
GestureDetector(
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => Register(),
),
);
},
child: const Text(
"No account yet? Register here...",
style: TextStyle(
color: Colors.blue,
fontStyle: FontStyle.italic,
decoration: TextDecoration.underline,
fontSize: 20.0,
),
),
)
],
),
)),
);
}
void login() async {
String url = "http://localhost/flutter/api/users.php";
final Map<String, dynamic> jsonData = {
"username": _usernameController.text,
"password": _passwordController.text
};
final Map<String, dynamic> queryParams = {
"operation": "login",
"json": jsonEncode(jsonData),
};
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) {
//navigate to next page
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => ContactsList(
userId: user[0]['usr_id'],
userFullName: user[0]['usr_fullname']),
),
);
} else {
setState(() {
_msg = "Invalid Username or password.";
});
}
} else {
setState(() {
_msg = "${response.statusCode} ${response.reasonPhrase}";
});
}
} catch (error) {
setState(() {
_msg = "$error";
});
}
}
}
register.dart
import 'dart:convert';
import 'package:db/functions/public_functions.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
class Register extends StatefulWidget {
const Register({Key? key}) : super(key: key);
@override
_RegisterState createState() => _RegisterState();
}
class _RegisterState extends State<Register> {
TextEditingController usernameController = TextEditingController();
TextEditingController passwordController = TextEditingController();
TextEditingController fullnameController = TextEditingController();
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text("Contacts Database"),
),
body: Center(
child: Padding(
padding: const EdgeInsets.all(20.0),
child: Column(
children: [
const Text(
"User Registration",
style: TextStyle(
fontSize: 20.0,
),
),
const SizedBox(
height: 20.0,
),
TextField(
controller: usernameController,
decoration: const InputDecoration(
labelText: "Username",
border: OutlineInputBorder(),
suffixIcon: Icon(Icons.person),
),
),
const SizedBox(
height: 10.0,
),
TextField(
controller: passwordController,
decoration: const InputDecoration(
labelText: "Password",
border: OutlineInputBorder(),
suffixIcon: Icon(Icons.password),
),
),
const SizedBox(
height: 10.0,
),
TextField(
controller: fullnameController,
decoration: const InputDecoration(
labelText: "Full Name",
border: OutlineInputBorder(),
suffixIcon: Icon(Icons.abc),
),
),
const SizedBox(
height: 20.0,
),
ElevatedButton(
onPressed: () {
save();
},
child: const Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(
Icons.save,
),
SizedBox(
width: 10.0,
),
Text("Save"),
],
),
),
],
),
),
),
);
}
void save() async {
Uri uri = Uri.parse('http://localhost/flutter/api/users.php');
Map<String, dynamic> jsonData = {
"username": usernameController.text,
"password": passwordController.text,
"fullname": fullnameController.text,
};
Map<String, dynamic> data = {
"operation": "register",
"json": jsonEncode(jsonData),
};
http.Response response = await http.post(uri, body: data);
if (response.statusCode == 200) {
if (response.body == "1") {
showMessageBox(context, "Success", "You have successfully registered!");
} else {
showMessageBox(context, "Error", "Registration failed!");
}
} else {
showMessageBox(context, "Error",
"The server returned a ${response.statusCode} error.");
}
}
}
No changes for other files.
No comments:
Post a Comment