php curd example - wordpress.com · 2020. 4. 4. · php curd example table of contents 1) simple...

35
PHP CURD EXAMPLE https://sbogreen.wordpress.com TABLE OF CONTENTS 1) simple example of curd ........................................................................................................................... 2 i. Config.php ........................................................................................................................................... 2 ii. index.php............................................................................................................................................. 2 iii. Create.php ....................................................................................................................................... 4 iv. delete.php ........................................................................................................................................ 7 v. read.php .............................................................................................................................................. 8 vi. update.php .................................................................................................................................... 10 2) Explaniaton ........................................................................................................................................... 14 I. Connecting to MySQL Database Server.................................................................................... 14 https://www.tutorialrepublic.com/php-tutorial/php-mysql-connect.php ............................................. 14 II. Closing the MySQL Database Server Connection ................................................................ 15 III. Creating MySQL Database Using PHP ................................................................................ 15 IV. Creating Tables inside MySQL Database Using PHP ........................................................... 16 V. Inserting Data into a MySQL Database Table......................................................................... 17 VI. Inserting Multiple Rows into a Table...................................................................................... 18 VII. Insert Data into a Database from an HTML Form ........................................................... 18 Step 1: Creating the HTML Form ....................................................................................................... 19 Step 2: Retrieving and Inserting the Form Data ............................................................................... 19 VIII. PHP MySQL Prepared Statements ...................................................................................... 20 What is Prepared Statement .................................................................................................................. 20 Advantages of Using Prepared Statements.......................................................................................... 21 Explanation of Code (Procedural style) ................................................................................................. 22 Using Inputs Received through a Web Form ....................................................................................... 22 IX. How to Get the ID of Last Inserted Row ............................................................................. 23 X. Selecting Data From Database Tables ................................................................................... 24 Explanation of Code (Procedural style) ................................................................................................. 25 XI. Filtering the Records ................................................................................................................ 26 XII. Limiting Result Sets ............................................................................................................... 27 XIII. Ordering the Result Set ........................................................................................................... 29 XIV. Updating Database Table Data ............................................................................................ 31

Upload: others

Post on 18-Sep-2020

19 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: PHP CURD EXAMPLE - WordPress.com · 2020. 4. 4. · PHP CURD EXAMPLE  TABLE OF CONTENTS 1) simple example of curd ..... 2 i. Config.php ..... 2

PHP CURD EXAMPLE https://sbogreen.wordpress.com

TABLE OF CONTENTS

1) simple example of curd ........................................................................................................................... 2

i. Config.php ........................................................................................................................................... 2

ii. index.php............................................................................................................................................. 2

iii. Create.php ....................................................................................................................................... 4

iv. delete.php ........................................................................................................................................ 7

v. read.php .............................................................................................................................................. 8

vi. update.php .................................................................................................................................... 10

2) Explaniaton ........................................................................................................................................... 14

I. Connecting to MySQL Database Server.................................................................................... 14

https://www.tutorialrepublic.com/php-tutorial/php-mysql-connect.php ............................................. 14

II. Closing the MySQL Database Server Connection ................................................................ 15

III. Creating MySQL Database Using PHP ................................................................................ 15

IV. Creating Tables inside MySQL Database Using PHP ........................................................... 16

V. Inserting Data into a MySQL Database Table......................................................................... 17

VI. Inserting Multiple Rows into a Table...................................................................................... 18

VII. Insert Data into a Database from an HTML Form ........................................................... 18

Step 1: Creating the HTML Form ....................................................................................................... 19

Step 2: Retrieving and Inserting the Form Data ............................................................................... 19

VIII. PHP MySQL Prepared Statements ...................................................................................... 20

What is Prepared Statement .................................................................................................................. 20

Advantages of Using Prepared Statements.......................................................................................... 21

Explanation of Code (Procedural style) ................................................................................................. 22

Using Inputs Received through a Web Form ....................................................................................... 22

IX. How to Get the ID of Last Inserted Row ............................................................................. 23

X. Selecting Data From Database Tables ................................................................................... 24

Explanation of Code (Procedural style) ................................................................................................. 25

XI. Filtering the Records ................................................................................................................ 26

XII. Limiting Result Sets ............................................................................................................... 27

XIII. Ordering the Result Set ........................................................................................................... 29

XIV. Updating Database Table Data ............................................................................................ 31

Page 2: PHP CURD EXAMPLE - WordPress.com · 2020. 4. 4. · PHP CURD EXAMPLE  TABLE OF CONTENTS 1) simple example of curd ..... 2 i. Config.php ..... 2

2

XV. Deleting Database Table Data ................................................................................................. 33

PHP MySQL CRUD Application ................................................................................................................. 35

PHP MySQL Ajax Live Search .................................................................................................................... 35

PHP MySQL Login System ......................................................................................................................... 35

1) SIMPLE EXAMPLE OF CURD

I. CONFIG.PHP

<?php

/* Database credentials. Assuming you are running MySQL

server with default setting (user 'root' with no password) */

define('DB_SERVER', 'localhost');

define('DB_USERNAME', 'root');

define('DB_PASSWORD', '');

define('DB_NAME', 'study');

/* Attempt to connect to MySQL database */

$link = mysqli_connect(DB_SERVER, DB_USERNAME, DB_PASSWORD, DB_NAME);

// Check connection

if($link === false){

die("ERROR: Could not connect. " . mysqli_connect_error());

}

?>

II. INDEX.PHP

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<title>Dashboard</title>

<link rel="stylesheet" href="./assets/bootstrap.css">

<link rel="stylesheet" href="./assets/bootstrap_maxcdn.css">

<script src="./assets/jquery.min.js"></script>

<script src="./assets/bootstrap.js"></script>

<style type="text/css">

.wrapper{

wtop_idth: 650px;

margin: 0 auto;

}

Page 3: PHP CURD EXAMPLE - WordPress.com · 2020. 4. 4. · PHP CURD EXAMPLE  TABLE OF CONTENTS 1) simple example of curd ..... 2 i. Config.php ..... 2

3

.page-header h2{

margin-top: 0;

}

table tr td:last-child a{

margin-right: 15px;

}

</style>

<script type="text/javascript">

$(document).ready(function(){

$('[data-toggle="tooltip"]').tooltip();

});

</script>

</head>

<body>

<div class="wrapper">

<div class="container-flutop_id">

<div class="row">

<div class="col-md-12">

<div class="page-header clearfix">

<h2 class="pull-left">View Topics</h2>

<a href="create.php" class="btn btn-success pull-

right">Add New Topic</a>

</div>

<?php

// Include config file

require_once "config.php";

// Attempt select query execution

$sql = "SELECT * FROM stu_topic";

if($result = mysqli_query($link, $sql)){

if(mysqli_num_rows($result) > 0){

echo "<table class='table table-bordered table-striped'>";

echo "<thead>";

echo "<tr>";

echo "<th>#</th>";

echo "<th>Topic</th>";

echo "<th>Description</th>";

echo "<th>Remarks</th>";

echo "<th>time</th>";

echo "</tr>";

echo "</thead>";

echo "<tbody>";

while($row = mysqli_fetch_array($result)){

echo "<tr>";

echo "<td>" . $row['top_id'] . "</td>";

echo "<td>" . $row['top_name'] . "</td>";

echo "<td>" . $row['top_desc'] . "</td>";

echo "<td>" . $row['top_rks'] . "</td>";

echo "<td>" . $row['top_time'] . "</td>";

echo "<td>";

echo "<a href='read.php?top_id=". $row['top_id'

] ."' title='View Record' data-toggle='tooltip'><span class='glyphicon glyphicon-eye-

open'>View</span></a>";

Page 4: PHP CURD EXAMPLE - WordPress.com · 2020. 4. 4. · PHP CURD EXAMPLE  TABLE OF CONTENTS 1) simple example of curd ..... 2 i. Config.php ..... 2

4

echo "<a href='update.php?top_id=". $row['top_i

d'] ."' title='Update Record' data-toggle='tooltip'><span class='glyphicon glyphicon-

pencil'>Update</span></a>";

echo "<a href='delete.php?top_id=". $row['top_i

d'] ."' title='Delete Record' data-toggle='tooltip'><span class='glyphicon glyphicon-

trash'>Delete</span></a>";

echo "</td>";

echo "</tr>";

}

echo "</tbody>";

echo "</table>";

// Free result set

mysqli_free_result($result);

} else{

echo "<p class='lead'><em>No records were found.</em></p>";

}

} else{

echo "ERROR: Could not able to execute $sql. " . mysqli_error($link

);

}

// Close connection

mysqli_close($link);

?>

</div>

</div>

</div>

</div>

</body>

</html>

III. CREATE.PHP

<?php

// Include config file

require_once "config.php";

// Define variables and initialize with empty values

$name = $address = $salary = "";

$name_err = $address_err = $salary_err = "";

// Processing form data when form is submitted

if($_SERVER["REQUEST_METHOD"] == "POST"){

// Validate name

$input_name = trim($_POST["name"]);

if(empty($input_name)){

$name_err = "Please enter a name.";

} elseif(!filter_var($input_name, FILTER_VALIDATE_REGEXP, array("options"=>array("regex

p"=>"/^[a-zA-Z\s]+$/")))){

Page 5: PHP CURD EXAMPLE - WordPress.com · 2020. 4. 4. · PHP CURD EXAMPLE  TABLE OF CONTENTS 1) simple example of curd ..... 2 i. Config.php ..... 2

5

$name_err = "Please enter a valid name.";

} else{

$name = $input_name;

}

// Validate address

$input_address = trim($_POST["address"]);

if(empty($input_address)){

$address_err = "Please enter an address.";

} else{

$address = $input_address;

}

// Validate salary

$input_salary = trim($_POST["salary"]);

if(empty($input_salary)){

$salary_err = "Please enter the salary amount.";

} elseif(!ctype_digit($input_salary)){

$salary_err = "Please enter a positive integer value.";

} else{

$salary = $input_salary;

}

// Check input errors before inserting in database

if(empty($name_err) && empty($address_err) && empty($salary_err)){

// Prepare an insert statement

$sql = "INSERT INTO employees (name, address, salary) VALUES (?, ?, ?)";

if($stmt = mysqli_prepare($link, $sql)){

// Bind variables to the prepared statement as parameters

mysqli_stmt_bind_param($stmt, "sss", $param_name, $param_address, $param_salary

);

// Set parameters

$param_name = $name;

$param_address = $address;

$param_salary = $salary;

// Attempt to execute the prepared statement

if(mysqli_stmt_execute($stmt)){

// Records created successfully. Redirect to landing page

header("location: index.php");

exit();

} else{

echo "Something went wrong. Please try again later.";

}

}

// Close statement

mysqli_stmt_close($stmt);

}

// Close connection

Page 6: PHP CURD EXAMPLE - WordPress.com · 2020. 4. 4. · PHP CURD EXAMPLE  TABLE OF CONTENTS 1) simple example of curd ..... 2 i. Config.php ..... 2

6

mysqli_close($link);

}

?>

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<title>Create Record</title>

<link rel="stylesheet" href="./assets/bootstrap.css">

<style type="text/css">

.wrapper{

width: 500px;

margin: 0 auto;

}

</style>

</head>

<body>

<div class="wrapper">

<div class="container-fluid">

<div class="row">

<div class="col-md-12">

<div class="page-header">

<h2>Create Record</h2>

</div>

<p>Please fill this form and submit to add employee record to the datab

ase.</p>

<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" me

thod="post">

<div class="form-group <?php echo (!empty($name_err)) ? 'has-

error' : ''; ?>">

<label>Topic Name</label>

<textarea name="name" class="form-

control" value="<?php echo $name; ?>"></textarea>

<span class="help-block"><?php echo $name_err;?></span>

</div>

<div class="form-group <?php echo (!empty($address_err)) ? 'has-

error' : ''; ?>">

<label>Address</label>

<textarea name="address" class="form-

control"><?php echo $address; ?></textarea>

<span class="help-block"><?php echo $address_err;?></span>

</div>

<div class="form-group <?php echo (!empty($salary_err)) ? 'has-

error' : ''; ?>">

<label>Salary</label>

<input type="text" name="salary" class="form-

control" value="<?php echo $salary; ?>">

<span class="help-block"><?php echo $salary_err;?></span>

</div>

<input type="submit" class="btn btn-primary" value="Submit">

<a href="index.php" class="btn btn-default">Cancel</a>

</form>

Page 7: PHP CURD EXAMPLE - WordPress.com · 2020. 4. 4. · PHP CURD EXAMPLE  TABLE OF CONTENTS 1) simple example of curd ..... 2 i. Config.php ..... 2

7

</div>

</div>

</div>

</div>

</body>

</html>

IV. DELETE.PHP

<?php

// Process delete operation after confirmation

if(isset($_POST["id"]) && !empty($_POST["id"])){

// Include config file

require_once "config.php";

// Prepare a delete statement

$sql = "DELETE FROM employees WHERE id = ?";

if($stmt = mysqli_prepare($link, $sql)){

// Bind variables to the prepared statement as parameters

mysqli_stmt_bind_param($stmt, "i", $param_id);

// Set parameters

$param_id = trim($_POST["id"]);

// Attempt to execute the prepared statement

if(mysqli_stmt_execute($stmt)){

// Records deleted successfully. Redirect to landing page

header("location: index.php");

exit();

} else{

echo "Oops! Something went wrong. Please try again later.";

}

}

// Close statement

mysqli_stmt_close($stmt);

// Close connection

mysqli_close($link);

} else{

// Check existence of id parameter

if(empty(trim($_GET["id"]))){

// URL doesn't contain id parameter. Redirect to error page

header("location: error.php");

exit();

}

}

Page 8: PHP CURD EXAMPLE - WordPress.com · 2020. 4. 4. · PHP CURD EXAMPLE  TABLE OF CONTENTS 1) simple example of curd ..... 2 i. Config.php ..... 2

8

?>

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<title>View Record</title>

<link rel="stylesheet" href="./assets/bootstrap.css">

<style type="text/css">

.wrapper{

width: 500px;

margin: 0 auto;

}

</style>

</head>

<body>

<div class="wrapper">

<div class="container-fluid">

<div class="row">

<div class="col-md-12">

<div class="page-header">

<h1>Delete Record</h1>

</div>

<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" me

thod="post">

<div class="alert alert-danger fade in">

<input type="hidden" name="id" value="<?php echo trim($_GET["id

"]); ?>"/>

<p>Are you sure you want to delete this record?</p><br>

<p>

<input type="submit" value="Yes" class="btn btn-danger">

<a href="index.php" class="btn btn-default">No</a>

</p>

</div>

</form>

</div>

</div>

</div>

</div>

</body>

</html>

V. READ.PHP

<?php

// Check existence of id parameter before processing further

if(isset($_GET["id"]) && !empty(trim($_GET["id"]))){

// Include config file

require_once "config.php";

Page 9: PHP CURD EXAMPLE - WordPress.com · 2020. 4. 4. · PHP CURD EXAMPLE  TABLE OF CONTENTS 1) simple example of curd ..... 2 i. Config.php ..... 2

9

// Prepare a select statement

$sql = "SELECT * FROM employees WHERE id = ?";

if($stmt = mysqli_prepare($link, $sql)){

// Bind variables to the prepared statement as parameters

mysqli_stmt_bind_param($stmt, "i", $param_id);

// Set parameters

$param_id = trim($_GET["id"]);

// Attempt to execute the prepared statement

if(mysqli_stmt_execute($stmt)){

$result = mysqli_stmt_get_result($stmt);

if(mysqli_num_rows($result) == 1){

/* Fetch result row as an associative array. Since the result set

contains only one row, we don't need to use while loop */

$row = mysqli_fetch_array($result, MYSQLI_ASSOC);

// Retrieve individual field value

$name = $row["name"];

$address = $row["address"];

$salary = $row["salary"];

} else{

// URL doesn't contain valid id parameter. Redirect to error page

header("location: error.php");

exit();

}

} else{

echo "Oops! Something went wrong. Please try again later.";

}

}

// Close statement

mysqli_stmt_close($stmt);

// Close connection

mysqli_close($link);

} else{

// URL doesn't contain id parameter. Redirect to error page

header("location: error.php");

exit();

}

?>

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<title>View Record</title>

<link rel="stylesheet" href="./assets/bootstrap.css">

<style type="text/css">

.wrapper{

Page 10: PHP CURD EXAMPLE - WordPress.com · 2020. 4. 4. · PHP CURD EXAMPLE  TABLE OF CONTENTS 1) simple example of curd ..... 2 i. Config.php ..... 2

10

width: 500px;

margin: 0 auto;

}

</style>

</head>

<body>

<div class="wrapper">

<div class="container-fluid">

<div class="row">

<div class="col-md-12">

<div class="page-header">

<h1>View Record</h1>

</div>

<div class="form-group">

<label>Name</label>

<p class="form-control-static"><?php echo $row["name"]; ?></p>

</div>

<div class="form-group">

<label>Address</label>

<p class="form-control-static"><?php echo $row["address"]; ?></p>

</div>

<div class="form-group">

<label>Salary</label>

<p class="form-control-static"><?php echo $row["salary"]; ?></p>

</div>

<p><a href="index.php" class="btn btn-primary">Back</a></p>

</div>

</div>

</div>

</div>

</body>

</html>

VI. UPDATE.PHP

<?php

// Include config file

require_once "config.php";

// Define variables and initialize with empty values

$name = $address = $salary = "";

$name_err = $address_err = $salary_err = "";

// Processing form data when form is submitted

if(isset($_POST["id"]) && !empty($_POST["id"])){

// Get hidden input value

$id = $_POST["id"];

Page 11: PHP CURD EXAMPLE - WordPress.com · 2020. 4. 4. · PHP CURD EXAMPLE  TABLE OF CONTENTS 1) simple example of curd ..... 2 i. Config.php ..... 2

11

// Validate name

$input_name = trim($_POST["name"]);

if(empty($input_name)){

$name_err = "Please enter a name.";

} elseif(!filter_var($input_name, FILTER_VALIDATE_REGEXP, array("options"=>array("regex

p"=>"/^[a-zA-Z\s]+$/")))){

$name_err = "Please enter a valid name.";

} else{

$name = $input_name;

}

// Validate address address

$input_address = trim($_POST["address"]);

if(empty($input_address)){

$address_err = "Please enter an address.";

} else{

$address = $input_address;

}

// Validate salary

$input_salary = trim($_POST["salary"]);

if(empty($input_salary)){

$salary_err = "Please enter the salary amount.";

} elseif(!ctype_digit($input_salary)){

$salary_err = "Please enter a positive integer value.";

} else{

$salary = $input_salary;

}

// Check input errors before inserting in database

if(empty($name_err) && empty($address_err) && empty($salary_err)){

// Prepare an update statement

$sql = "UPDATE employees SET name=?, address=?, salary=? WHERE id=?";

if($stmt = mysqli_prepare($link, $sql)){

// Bind variables to the prepared statement as parameters

mysqli_stmt_bind_param($stmt, "sssi", $param_name, $param_address, $param_salar

y, $param_id);

// Set parameters

$param_name = $name;

$param_address = $address;

$param_salary = $salary;

$param_id = $id;

// Attempt to execute the prepared statement

if(mysqli_stmt_execute($stmt)){

// Records updated successfully. Redirect to landing page

header("location: index.php");

exit();

} else{

echo "Something went wrong. Please try again later.";

}

Page 12: PHP CURD EXAMPLE - WordPress.com · 2020. 4. 4. · PHP CURD EXAMPLE  TABLE OF CONTENTS 1) simple example of curd ..... 2 i. Config.php ..... 2

12

}

// Close statement

mysqli_stmt_close($stmt);

}

// Close connection

mysqli_close($link);

} else{

// Check existence of id parameter before processing further

if(isset($_GET["id"]) && !empty(trim($_GET["id"]))){

// Get URL parameter

$id = trim($_GET["id"]);

// Prepare a select statement

$sql = "SELECT * FROM employees WHERE id = ?";

if($stmt = mysqli_prepare($link, $sql)){

// Bind variables to the prepared statement as parameters

mysqli_stmt_bind_param($stmt, "i", $param_id);

// Set parameters

$param_id = $id;

// Attempt to execute the prepared statement

if(mysqli_stmt_execute($stmt)){

$result = mysqli_stmt_get_result($stmt);

if(mysqli_num_rows($result) == 1){

/* Fetch result row as an associative array. Since the result set

contains only one row, we don't need to use while loop */

$row = mysqli_fetch_array($result, MYSQLI_ASSOC);

// Retrieve individual field value

$name = $row["name"];

$address = $row["address"];

$salary = $row["salary"];

} else{

// URL doesn't contain valid id. Redirect to error page

header("location: error.php");

exit();

}

} else{

echo "Oops! Something went wrong. Please try again later.";

}

}

// Close statement

mysqli_stmt_close($stmt);

// Close connection

mysqli_close($link);

} else{

Page 13: PHP CURD EXAMPLE - WordPress.com · 2020. 4. 4. · PHP CURD EXAMPLE  TABLE OF CONTENTS 1) simple example of curd ..... 2 i. Config.php ..... 2

13

// URL doesn't contain id parameter. Redirect to error page

header("location: error.php");

exit();

}

}

?>

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<title>Update Record</title>

<link rel="stylesheet" href="./assets/bootstrap.css">

<style type="text/css">

.wrapper{

width: 500px;

margin: 0 auto;

}

</style>

</head>

<body>

<div class="wrapper">

<div class="container-fluid">

<div class="row">

<div class="col-md-12">

<div class="page-header">

<h2>Update Record</h2>

</div>

<p>Please edit the input values and submit to update the record.</p>

<form action="<?php echo htmlspecialchars(basename($_SERVER['REQUEST_UR

I'])); ?>" method="post">

<div class="form-group <?php echo (!empty($name_err)) ? 'has-

error' : ''; ?>">

<label>Name</label>

<input type="text" name="name" class="form-

control" value="<?php echo $name; ?>">

<span class="help-block"><?php echo $name_err;?></span>

</div>

<div class="form-group <?php echo (!empty($address_err)) ? 'has-

error' : ''; ?>">

<label>Address</label>

<textarea name="address" class="form-

control"><?php echo $address; ?></textarea>

<span class="help-block"><?php echo $address_err;?></span>

</div>

<div class="form-group <?php echo (!empty($salary_err)) ? 'has-

error' : ''; ?>">

<label>Salary</label>

<input type="text" name="salary" class="form-

control" value="<?php echo $salary; ?>">

<span class="help-block"><?php echo $salary_err;?></span>

</div>

<input type="hidden" name="id" value="<?php echo $id; ?>"/>

Page 14: PHP CURD EXAMPLE - WordPress.com · 2020. 4. 4. · PHP CURD EXAMPLE  TABLE OF CONTENTS 1) simple example of curd ..... 2 i. Config.php ..... 2

14

<input type="submit" class="btn btn-primary" value="Submit">

<a href="index.php" class="btn btn-default">Cancel</a>

</form>

</div>

</div>

</div>

</div>

</body>

</html>

2) EXPLANIATON

I. CONNECTING TO MYSQL DATABASE SERVER

In PHP you can easily do this using the mysqli_connect() function. All communication between PHP and

the MySQL database server takes place through this connection. Here're the basic syntaxes for connecting to

MySQL using MySQLi and PDO extensions:

Syntax: MySQLi, Procedural way

$link = mysqli_connect("hostname", "username", "password", "database");

Syntax: MySQLi, Object Oriented way

$mysqli = new mysqli("hostname", "username", "password", "database");

Syntax: PHP Data Objects (PDO) way

$pdo = new PDO("mysql:host=hostname;dbname=database", "username", "password");

The hostname parameter in the above syntax specify the host name (e.g. localhost), or IP address of the

MySQL server, whereas the username and password parameters specifies the credentials to access MySQL

server, and the database parameter, if provided will specify the default MySQL database to be used when

performing queries.

The following example shows how to connect to MySQL database server using MySQLi

(both procedural and object oriented way) and PDO extension.

HTTPS://WWW.TUTORIALREPUBLIC.COM/PHP-TUTORIAL/PHP-MYSQL-CONNECT.PHP

<?PHP /* ATTEMPT MYSQL SERVER CONNECTION. ASSUMING YOU ARE RUNNING MYSQL

SERVER WITH DEFAULT SETTING (USER 'ROOT' WITH NO PASSWORD) */

$LINK = MYSQLI_CONNECT("LOCALHOST", "ROOT", "");

Page 15: PHP CURD EXAMPLE - WordPress.com · 2020. 4. 4. · PHP CURD EXAMPLE  TABLE OF CONTENTS 1) simple example of curd ..... 2 i. Config.php ..... 2

15

// CHECK CONNECTION IF($LINK === FALSE){ DIE("ERROR: COULD NOT CONNECT. " .

MYSQLI_CONNECT_ERROR()); }

// PRINT HOST INFORMATION ECHO "CONNECT SUCCESSFULLY. HOST INFO: " .

MYSQLI_GET_HOST_INFO($LINK); ?>

II. CLOSING THE MYSQL DATABASE SERVER CONNECTION

The connection to the MySQL database server will be closed automatically as soon as the

execution of the script ends. However, if you want to close it earlier you can do this by

simply calling the PHP mysqli_close() function.

<?php /* Attempt MySQL server connection. Assuming you are running MySQL server with default setting (user 'root' with no password) */ $link = mysqli_connect("localhost", "root", ""); // Check connection if($link === false){ die("ERROR: Could not connect. " . mysqli_connect_error()); } // Print host information echo "Connect Successfully. Host info: " . mysqli_get_host_info($link); // Close connection mysqli_close($link); ?>

III. CREATING MYSQL DATABASE USING PHP

Now that you've understood how to open a connection to the MySQL database server. In

this tutorial you will learn how to execute SQL query to create a database.

Before saving or accessing the data, we need to create a database first. The CREATE

DATABASE statement is used to create a new database in MySQL.

Let's make a SQL query using the CREATE DATABASE statement, after that we will execute this

SQL query through passing it to the PHP mysqli_query() function to finally create our

database. The following example creates a database named demo.

<?php /* Attempt MySQL server connection. Assuming you are running MySQL

Page 16: PHP CURD EXAMPLE - WordPress.com · 2020. 4. 4. · PHP CURD EXAMPLE  TABLE OF CONTENTS 1) simple example of curd ..... 2 i. Config.php ..... 2

16

server with default setting (user 'root' with no password) */ $link = mysqli_connect("localhost", "root", ""); // Check connection if($link === false){ die("ERROR: Could not connect. " . mysqli_connect_error()); } // Attempt create database query execution $sql = "CREATE DATABASE demo"; if(mysqli_query($link, $sql)){ echo "Database created successfully"; } else{ echo "ERROR: Could not able to execute $sql. " . mysqli_error($link); } // Close connection mysqli_close($link); ?>

IV. CREATING TABLES INSIDE MYSQL DATABASE USING PHP

In the previous chapter we've learned how to create a database on MySQL server. Now it's

time to create some tables inside the database that will actually hold the data. A table

organizes the information into rows and columns.

The SQL CREATE TABLE statement is used to create a table in database.

Let's make a SQL query using the CREATE TABLE statement, after that we will execute this SQL

query through passing it to the PHP mysqli_query() function to finally create our table.

<?php /* Attempt MySQL server connection. Assuming you are running MySQL server with default setting (user 'root' with no password) */ $link = mysqli_connect("localhost", "root", "", "demo"); // Check connection if($link === false){ die("ERROR: Could not connect. " . mysqli_connect_error()); } // Attempt create table query execution $sql = "CREATE TABLE persons( id INT NOT NULL PRIMARY KEY AUTO_INCREMENT, first_name VARCHAR(30) NOT NULL, last_name VARCHAR(30) NOT NULL, email VARCHAR(70) NOT NULL UNIQUE )"; if(mysqli_query($link, $sql)){ echo "Table created successfully."; } else{

Page 17: PHP CURD EXAMPLE - WordPress.com · 2020. 4. 4. · PHP CURD EXAMPLE  TABLE OF CONTENTS 1) simple example of curd ..... 2 i. Config.php ..... 2

17

echo "ERROR: Could not able to execute $sql. " . mysqli_error($link); } // Close connection mysqli_close($link); ?>

V. INSERTING DATA INTO A MYSQL DATABASE TABLE Now that you've understood how to create database and tables in MySQL. In this tutorial

you will learn how to execute SQL query to insert records into a table.

The INSERT INTO statement is used to insert new rows in a database table.

Let's make a SQL query using the INSERT INTO statement with appropriate values, after that

we will execute this insert query through passing it to the PHP mysqli_query() function to

insert data in table. Here's an example, which insert a new row to the persons table by

specifying values for the first_name, last_name and email fields.

<?php /* Attempt MySQL server connection. Assuming you are running MySQL server with default setting (user 'root' with no password) */ $link = mysqli_connect("localhost", "root", "", "demo"); // Check connection if($link === false){ die("ERROR: Could not connect. " . mysqli_connect_error()); } // Attempt insert query execution $sql = "INSERT INTO persons (first_name, last_name, email) VALUES ('Peter', 'Parker', '[email protected]')"; if(mysqli_query($link, $sql)){ echo "Records inserted successfully."; } else{ echo "ERROR: Could not able to execute $sql. " . mysqli_error($link); } // Close connection mysqli_close($link); ?>

If you remember from the preceding chapter, the id field was marked with

the AUTO_INCREMENT flag. This modifier tells the MySQL to automatically assign a value to this

field if it is left unspecified, by incrementing the previous value by 1.

Page 18: PHP CURD EXAMPLE - WordPress.com · 2020. 4. 4. · PHP CURD EXAMPLE  TABLE OF CONTENTS 1) simple example of curd ..... 2 i. Config.php ..... 2

18

VI. INSERTING MULTIPLE ROWS INTO A TABLE You can also insert multiple rows into a table with a single insert query at once. To do this,

include multiple lists of column values within the INSERT INTO statement, where column

values for each row must be enclosed within parentheses and separated by a comma.

Let's insert few more rows into the persons table, like this:

Example

Procedural Object Oriented PDO

Download <?php /* Attempt MySQL server connection. Assuming you are running MySQL server with default setting (user 'root' with no password) */ $link = mysqli_connect("localhost", "root", "", "demo"); // Check connection if($link === false){ die("ERROR: Could not connect. " . mysqli_connect_error()); } // Attempt insert query execution $sql = "INSERT INTO persons (first_name, last_name, email) VALUES ('John', 'Rambo', '[email protected]'), ('Clark', 'Kent', '[email protected]'), ('John', 'Carter', '[email protected]'), ('Harry', 'Potter', '[email protected]')"; if(mysqli_query($link, $sql)){ echo "Records added successfully."; } else{ echo "ERROR: Could not able to execute $sql. " . mysqli_error($link); } // Close connection mysqli_close($link); ?>

Now, go to phpMyAdmin (http://localhost/phpmyadmin/) and check out the persons table

data inside demo database. You will find the value for the id column is assigned

automatically by incrementing the value of previous id by 1.

VII. INSERT DATA INTO A DATABASE FROM AN HTML FORM

In the previous section, we have learned how to insert data into database from a PHP script.

Now, we'll see how we can insert data into database obtained from an HTML form. Let's

create an HTML form that can be used to insert new records to persons table.

Page 19: PHP CURD EXAMPLE - WordPress.com · 2020. 4. 4. · PHP CURD EXAMPLE  TABLE OF CONTENTS 1) simple example of curd ..... 2 i. Config.php ..... 2

19

STEP 1: CREATING THE HTML FORM

Here's a simple HTML form that has three text <input> fields and a submit button.

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Add Record Form</title> </head> <body> <form action="insert.php" method="post"> <p> <label for="firstName">First Name:</label> <input type="text" name="first_name" id="firstName"> </p> <p> <label for="lastName">Last Name:</label> <input type="text" name="last_name" id="lastName"> </p> <p> <label for="emailAddress">Email Address:</label> <input type="text" name="email" id="emailAddress"> </p> <input type="submit" value="Submit"> </form> </body> </html>

STEP 2: RETRIEVING AND INSERTING THE FORM DATA

When a user clicks the submit button of the add record HTML form, in the example above,

the form data is sent to 'insert.php' file. The 'insert.php' file connects to the MySQL database

server, retrieves forms fields using the PHP $_REQUEST variables and finally execute the insert

query to add the records. Here is the complete code of our 'insert.php' file:

<?php /* Attempt MySQL server connection. Assuming you are running MySQL server with default setting (user 'root' with no password) */ $link = mysqli_connect("localhost", "root", "", "demo"); // Check connection if($link === false){ die("ERROR: Could not connect. " . mysqli_connect_error()); } // Escape user inputs for security $first_name = mysqli_real_escape_string($link, $_REQUEST['first_name']); $last_name = mysqli_real_escape_string($link, $_REQUEST['last_name']); $email = mysqli_real_escape_string($link, $_REQUEST['email']); // Attempt insert query execution $sql = "INSERT INTO persons (first_name, last_name, email) VALUES ('$first_name', '$last_name', '$email')";

Page 20: PHP CURD EXAMPLE - WordPress.com · 2020. 4. 4. · PHP CURD EXAMPLE  TABLE OF CONTENTS 1) simple example of curd ..... 2 i. Config.php ..... 2

20

if(mysqli_query($link, $sql)){ echo "Records added successfully."; } else{ echo "ERROR: Could not able to execute $sql. " . mysqli_error($link); } // Close connection mysqli_close($link); ?>

In the next chapter we will extend this insert query example and take it one step further by

implementing the prepared statement for better security and performance.

Note: The mysqli_real_escape_string() function escapes special characters in a string and

create a legal SQL string to provide security against SQL injection.

This is very basic example of inserting the form data in a MySQL database table. You can

extend this example and make it more interactive by adding validations to the user inputs

before inserting it to the database tables. Please check out the tutorial on PHP form

validation to learn more about sanitizing and validating user inputs using PHP.

VIII. PHP MYSQL PREPARED STATEMENTS

WHAT IS PREPARED STATEMENT

A prepared statement (also known as parameterized statement) is simply a SQL query

template containing placeholder instead of the actual parameter values. These placeholders

will be replaced by the actual values at the time of execution of the statement.

MySQLi supports the use of anonymous positional placeholder (?), as shown below:

INSERT INTO persons (first_name, last_name, email) VALUES (?, ?, ?);

While, PDO supports both anonymous positional placeholder (?), as well as the named

placeholders. A named placeholder begins with a colon (:) followed by an identifier, like this:

INSERT INTO persons (first_name, last_name, email) VALUES (:first_name, :last_name, :email);

The prepared statement execution consists of two stages: prepare and execute.

Prepare — At the prepare stage a SQL statement template is created and sent to the

database server. The server parses the statement template, performs a syntax check and

query optimization, and stores it for later use.

Execute — During execute the parameter values are sent to the server. The server creates a

statement from the statement template and these values to execute it.

Prepared statements is very useful, particularly in situations when you execute a particular

statement multiple times with different values, for example, a series of INSERT statements.

The following section describes some of the major benefits of using it.

Page 21: PHP CURD EXAMPLE - WordPress.com · 2020. 4. 4. · PHP CURD EXAMPLE  TABLE OF CONTENTS 1) simple example of curd ..... 2 i. Config.php ..... 2

21

ADVANTAGES OF USING PREPARED STATEMENTS

A prepared statement can execute the same statement repeatedly with high efficiency,

because the statement is parsed only once again, while it can be executed multiple times. It

also minimize bandwidth usage, since upon every execution only the placeholder values

need to be transmitted to the database server instead of the complete SQL statement.

Prepared statements also provide strong protection against SQL injection, because

parameter values are not embedded directly inside the SQL query string. The parameter

values are sent to the database server separately from the query using a different protocol

and thus cannot interfere with it. The server uses these values directly at the point of

execution, after the statement template is parsed. That's why the prepared statements are

less error-prone, and thus considered as one of the most critical element in database

security.

The following example will show you how prepared statements actually work:

<?php /* Attempt MySQL server connection. Assuming you are running MySQL server with default setting (user 'root' with no password) */ $link = mysqli_connect("localhost", "root", "", "demo"); // Check connection if($link === false){ die("ERROR: Could not connect. " . mysqli_connect_error()); } // Prepare an insert statement $sql = "INSERT INTO persons (first_name, last_name, email) VALUES (?, ?, ?)"; if($stmt = mysqli_prepare($link, $sql)){ // Bind variables to the prepared statement as parameters mysqli_stmt_bind_param($stmt, "sss", $first_name, $last_name, $email); /* Set the parameters values and execute the statement again to insert another row */ $first_name = "Hermione"; $last_name = "Granger"; $email = "[email protected]"; mysqli_stmt_execute($stmt); /* Set the parameters values and execute the statement to insert a row */ $first_name = "Ron"; $last_name = "Weasley"; $email = "[email protected]"; mysqli_stmt_execute($stmt); echo "Records inserted successfully."; } else{ echo "ERROR: Could not prepare query: $sql. " . mysqli_error($link); }

Page 22: PHP CURD EXAMPLE - WordPress.com · 2020. 4. 4. · PHP CURD EXAMPLE  TABLE OF CONTENTS 1) simple example of curd ..... 2 i. Config.php ..... 2

22

// Close statement mysqli_stmt_close($stmt); // Close connection mysqli_close($link); ?>

As you can see in the above example we've prepared the INSERT statement just once but

executed it multiple times by passing the different set of parameters.

EXPLANATION OF CODE (PROCEDURAL STYLE)

Inside the SQL INSERT statement (line no-12) of the example above, the question marks is

used as the placeholders for the first_name, last_name, email fields values.

The mysqli_stmt_bind_param() function (line no-16) bind variables to the placeholders (?) in

the SQL statement template. The placeholders (?) will be replaced by the actual values held

in the variables at the time of execution. The type definition string provided as second

argument i.e. the "sss" string specifies that the data type of each bind variable is string.

The type definition string specify the data types of the corresponding bind variables and

contains one or more of the following four characters:

b — binary (such as image, PDF file, etc.)

d — double (floating point number)

i — integer (whole number)

s — string (text)

The number of bind variables and the number of characters in type definition string must

match the number of placeholders in the SQL statement template.

USING INPUTS RECEIVED THROUGH A WEB FORM

If you remember from the previous chapter, we've created an HTML form to insert data into

database. Here, we're going to extend that example by implementing the prepared

statement. You can use the same HTML form to test the following insert script example, but

just make sure that you're using the correct file name in the action attribute of the form.

Here's the updated PHP code for inserting the data. If you see the example carefully you'll

find we didn't use the mysqli_real_escape_string() to escape the user inputs, like we've

done in the previous chapter example. Since in prepared statements, user inputs are never

substituted into the query string directly, so they do not need to be escaped correctly.

<?php /* Attempt MySQL server connection. Assuming you are running MySQL server with default setting (user 'root' with no password) */ $link = mysqli_connect("localhost", "root", "", "demo");

Page 23: PHP CURD EXAMPLE - WordPress.com · 2020. 4. 4. · PHP CURD EXAMPLE  TABLE OF CONTENTS 1) simple example of curd ..... 2 i. Config.php ..... 2

23

// Check connection if($link === false){ die("ERROR: Could not connect. " . mysqli_connect_error()); } // Prepare an insert statement $sql = "INSERT INTO persons (first_name, last_name, email) VALUES (?, ?, ?)"; if($stmt = mysqli_prepare($link, $sql)){ // Bind variables to the prepared statement as parameters mysqli_stmt_bind_param($stmt, "sss", $first_name, $last_name, $email); // Set parameters $first_name = $_REQUEST['first_name']; $last_name = $_REQUEST['last_name']; $email = $_REQUEST['email']; // Attempt to execute the prepared statement if(mysqli_stmt_execute($stmt)){ echo "Records inserted successfully."; } else{ echo "ERROR: Could not execute query: $sql. " . mysqli_error($link); } } else{ echo "ERROR: Could not prepare query: $sql. " . mysqli_error($link); } // Close statement mysqli_stmt_close($stmt); // Close connection mysqli_close($link); ?>

Note: Though escaping user inputs is not required in prepared statements, you should

always validate the type and size of the data received from external sources and enforces

appropriate limits to protect against system resources exploitation.

IX. HOW TO GET THE ID OF LAST INSERTED ROW In the PHP MySQL insert chapter you've learnt MySQL automatically generate an unique ID

for the AUTO_INCREMENT column each time you insert a new record or row into the table.

However, there are certain situations when you need that automatically generated ID to

insert it into a second table. In these situations you can use the

PHP mysqli_insert_id() function to retrieve the most recently generated ID, as shown in the

upcoming example.

For this example we'll use the same persons table that we've created in the PHP MySQL

create tables chapter, which has four columns id, first_name, last_name and email,

where id is the primary key column and marked with AUTO_INCREMENT flag.

Page 24: PHP CURD EXAMPLE - WordPress.com · 2020. 4. 4. · PHP CURD EXAMPLE  TABLE OF CONTENTS 1) simple example of curd ..... 2 i. Config.php ..... 2

24

Download <?php /* Attempt MySQL server connection. Assuming you are running MySQL server with default setting (user 'root' with no password) */ $link = mysqli_connect("localhost", "root", "", "demo"); // Check connection if($link === false){ die("ERROR: Could not connect. " . mysqli_connect_error()); } // Attempt insert query execution $sql = "INSERT INTO persons (first_name, last_name, email) VALUES ('Ron', 'Weasley', '[email protected]')"; if(mysqli_query($link, $sql)){ // Obtain last inserted id $last_id = mysqli_insert_id($link); echo "Records inserted successfully. Last inserted ID is: " . $last_id; } else{ echo "ERROR: Could not able to execute $sql. " . mysqli_error($link); } // Close connection mysqli_close($link); ?>

X. SELECTING DATA FROM DATABASE TABLES

So far you have learnt how to create database and table as well as inserting data. Now it's

time to retrieve data what have inserted in the preceding tutorial. The SQL SELECT statement

is used to select the records from database tables. Its basic syntax is as follows:

SELECT column1_name, column2_name, columnN_name FROM table_name;

Let's make a SQL query using the SELECT statement, after that we will execute this SQL query

through passing it to the PHP mysqli_query() function to retrieve the table data.

Consider our persons database table has the following records:

+----+------------+-----------+----------------------+

| id | first_name | last_name | email |

+----+------------+-----------+----------------------+

| 1 | Peter | Parker | [email protected] |

| 2 | John | Rambo | [email protected] |

| 3 | Clark | Kent | [email protected] |

| 4 | John | Carter | [email protected] |

Page 25: PHP CURD EXAMPLE - WordPress.com · 2020. 4. 4. · PHP CURD EXAMPLE  TABLE OF CONTENTS 1) simple example of curd ..... 2 i. Config.php ..... 2

25

| 5 | Harry | Potter | [email protected] |

+----+------------+-----------+----------------------+

The PHP code in the following example selects all the data stored in the persons table (using

the asterisk character (*) in place of column name selects all the data in the table).

<?php /* Attempt MySQL server connection. Assuming you are running MySQL server with default setting (user 'root' with no password) */ $link = mysqli_connect("localhost", "root", "", "demo"); // Check connection if($link === false){ die("ERROR: Could not connect. " . mysqli_connect_error()); } // Attempt select query execution $sql = "SELECT * FROM persons"; if($result = mysqli_query($link, $sql)){ if(mysqli_num_rows($result) > 0){ echo "<table>"; echo "<tr>"; echo "<th>id</th>"; echo "<th>first_name</th>"; echo "<th>last_name</th>"; echo "<th>email</th>"; echo "</tr>"; while($row = mysqli_fetch_array($result)){ echo "<tr>"; echo "<td>" . $row['id'] . "</td>"; echo "<td>" . $row['first_name'] . "</td>"; echo "<td>" . $row['last_name'] . "</td>"; echo "<td>" . $row['email'] . "</td>"; echo "</tr>"; } echo "</table>"; // Free result set mysqli_free_result($result); } else{ echo "No records matching your query were found."; } } else{ echo "ERROR: Could not able to execute $sql. " . mysqli_error($link); } // Close connection mysqli_close($link); ?>

EXPLANATION OF CODE (PROCEDURAL STYLE)

In the example above, the data returned by the mysqli_query() function is stored in

the $result variable. Each time mysqli_fetch_array() is invoked, it returns the next row from

Page 26: PHP CURD EXAMPLE - WordPress.com · 2020. 4. 4. · PHP CURD EXAMPLE  TABLE OF CONTENTS 1) simple example of curd ..... 2 i. Config.php ..... 2

26

the result set as an array. The while loop is used to loops through all the rows in the result

set. Finally the value of individual field can be accessed from the row either by passing the

field index or field name to the $row variable

like $row['id'] or $row[0], $row['first_name'] or $row[1], $row['last_name'] or $row[2],

and $row['email'] or $row[3].

If you want to use the for loop you can obtain the loop counter value or the number of rows

returned by the query by passing the $result variable to the mysqli_num_rows() function. This

loop counter value determines how many times the loop should run.

XI. FILTERING THE RECORDS The WHERE clause is used to extract only those records that fulfill a specified condition.

The basic syntax of the WHERE clause can be given with:

SELECT column_name(s) FROM table_name WHERE column_name operator value Let's make a SQL query using the WHERE clause in SELECT statement, after that we'll execute this query

through passing it to the PHP mysqli_query() function to get the filtered data.

Consider we've a persons table inside the demo database that has following records:

+----+------------+-----------+----------------------+

| id | first_name | last_name | email |

+----+------------+-----------+----------------------+

| 1 | Peter | Parker | [email protected] |

| 2 | John | Rambo | [email protected] |

| 3 | Clark | Kent | [email protected] |

| 4 | John | Carter | [email protected] |

| 5 | Harry | Potter | [email protected] |

+----+------------+-----------+----------------------+

The following PHP code selects all the rows from the persons table where first_name='john':

<?php /* Attempt MySQL server connection. Assuming you are running MySQL server with default setting (user 'root' with no password) */ $link = mysqli_connect("localhost", "root", "", "demo"); // Check connection if($link === false){ die("ERROR: Could not connect. " . mysqli_connect_error()); }

Page 27: PHP CURD EXAMPLE - WordPress.com · 2020. 4. 4. · PHP CURD EXAMPLE  TABLE OF CONTENTS 1) simple example of curd ..... 2 i. Config.php ..... 2

27

// Attempt select query execution $sql = "SELECT * FROM persons WHERE first_name='john'"; if($result = mysqli_query($link, $sql)){ if(mysqli_num_rows($result) > 0){ echo "<table>"; echo "<tr>"; echo "<th>id</th>"; echo "<th>first_name</th>"; echo "<th>last_name</th>"; echo "<th>email</th>"; echo "</tr>"; while($row = mysqli_fetch_array($result)){ echo "<tr>"; echo "<td>" . $row['id'] . "</td>"; echo "<td>" . $row['first_name'] . "</td>"; echo "<td>" . $row['last_name'] . "</td>"; echo "<td>" . $row['email'] . "</td>"; echo "</tr>"; } echo "</table>"; // Close result set mysqli_free_result($result); } else{ echo "No records matching your query were found."; } } else{ echo "ERROR: Could not able to execute $sql. " . mysqli_error($link); } // Close connection mysqli_close($link); ?> After filtration the result set will look something like this:

+----+------------+-----------+---------------------+

| id | first_name | last_name | email |

+----+------------+-----------+---------------------+

| 2 | John | Rambo | [email protected] |

| 4 | John | Carter | [email protected] |

XII. LIMITING RESULT SETS The LIMIT clause is used to constrain the number of rows returned by the SELECT statement. This feature is

very helpful for optimizing the page loading time as well as to enhance the readability of a website. For

example you can divide the large number of records in multiple pages using pagination, where limited number

of records will be loaded on every page from the database when a user request for that page by clicking on pagination link.

Page 28: PHP CURD EXAMPLE - WordPress.com · 2020. 4. 4. · PHP CURD EXAMPLE  TABLE OF CONTENTS 1) simple example of curd ..... 2 i. Config.php ..... 2

28

The basic syntax of the LIMIT clause can be given with:

SELECT column_name(s) FROM table_name LIMIT row_offset, row_count; The LIMIT clause accepts one or two parameters which must be a nonnegative integer:

When two parameters are specified, the first parameter specifies the offset of the first row to return i.e. the starting point, whereas the second parameter specifies the number of rows to return. The offset of the first row is 0 (not 1).

Whereas, when only one parameter is given, it specifies the maximum number of rows to return from the beginning of the result set.

For example, to retrieve the first three rows, you can use the following query:

SELECT * FROM persons LIMIT 3; To retrieve the rows 2-4 (inclusive) of a result set, you can use the following query:

SELECT * FROM persons LIMIT 1, 3; Let's make a SQL query using the LIMIT clause in SELECT statement, after that we will execute this query

through passing it to the PHP mysqli_query() function to get the limited number of records. Consider the following persons table inside the demo database:

+----+------------+-----------+----------------------+

| id | first_name | last_name | email |

+----+------------+-----------+----------------------+

| 1 | Peter | Parker | [email protected] |

| 2 | John | Rambo | [email protected] |

| 3 | Clark | Kent | [email protected] |

| 4 | John | Carter | [email protected] |

| 5 | Harry | Potter | [email protected] |

+----+------------+-----------+----------------------+

The PHP code in the following example will display just three rows from the persons table.

<?php /* Attempt MySQL server connection. Assuming you are running MySQL server with default setting (user 'root' with no password) */ $link = mysqli_connect("localhost", "root", "", "demo"); // Check connection if($link === false){ die("ERROR: Could not connect. " . mysqli_connect_error()); } // Attempt select query execution $sql = "SELECT * FROM persons LIMIT 3"; if($result = mysqli_query($link, $sql)){ if(mysqli_num_rows($result) > 0){ echo "<table>"; echo "<tr>"; echo "<th>id</th>";

Page 29: PHP CURD EXAMPLE - WordPress.com · 2020. 4. 4. · PHP CURD EXAMPLE  TABLE OF CONTENTS 1) simple example of curd ..... 2 i. Config.php ..... 2

29

echo "<th>first_name</th>"; echo "<th>last_name</th>"; echo "<th>email</th>"; echo "</tr>"; while($row = mysqli_fetch_array($result)){ echo "<tr>"; echo "<td>" . $row['id'] . "</td>"; echo "<td>" . $row['first_name'] . "</td>"; echo "<td>" . $row['last_name'] . "</td>"; echo "<td>" . $row['email'] . "</td>"; echo "</tr>"; } echo "</table>"; // Close result set mysqli_free_result($result); } else{ echo "No records matching your query were found."; } } else{ echo "ERROR: Could not able to execute $sql. " . mysqli_error($link); } // Close connection mysqli_close($link); ?> After limiting the result set the output will look something like this:

+----+------------+-----------+----------------------+

| id | first_name | last_name | email |

+----+------------+-----------+----------------------+

| 1 | Peter | Parker | [email protected] |

| 2 | John | Rambo | [email protected] |

| 3 | Clark | Kent | [email protected] |

XIII. ORDERING THE RESULT SET The ORDER BY clause can be used in conjugation with the SELECT statement to see the data

from a table ordered by a specific field. The ORDER BY clause lets you define the field name to

sort against and the sort direction either ascending or descending.

The basic syntax of this clause can be given with:

SELECT column_name(s) FROM table_name ORDER BY column_name(s) ASC|DESC

Page 30: PHP CURD EXAMPLE - WordPress.com · 2020. 4. 4. · PHP CURD EXAMPLE  TABLE OF CONTENTS 1) simple example of curd ..... 2 i. Config.php ..... 2

30

Let's make a SQL query using the ORDER BY clause in SELECT statement, after that we will

execute this query through passing it to the PHP mysqli_query() function to get the ordered

data. Consider the following persons table inside the demo database:

+----+------------+-----------+----------------------+

| id | first_name | last_name | email |

+----+------------+-----------+----------------------+

| 1 | Peter | Parker | [email protected] |

| 2 | John | Rambo | [email protected] |

| 3 | Clark | Kent | [email protected] |

| 4 | John | Carter | [email protected] |

| 5 | Harry | Potter | [email protected] |

+----+------------+-----------+----------------------+

The PHP code in the following example selects all rows from the persons table and sorts the

result by the first_name column in the alphabetically ascending order.

Example

Procedural Object Oriented PDO

Download <?php /* Attempt MySQL server connection. Assuming you are running MySQL server with default setting (user 'root' with no password) */ $link = mysqli_connect("localhost", "root", "", "demo"); // Check connection if($link === false){ die("ERROR: Could not connect. " . mysqli_connect_error()); } // Attempt select query execution with order by clause $sql = "SELECT * FROM persons ORDER BY first_name"; if($result = mysqli_query($link, $sql)){ if(mysqli_num_rows($result) > 0){ echo "<table>"; echo "<tr>"; echo "<th>id</th>"; echo "<th>first_name</th>"; echo "<th>last_name</th>"; echo "<th>email</th>"; echo "</tr>"; while($row = mysqli_fetch_array($result)){ echo "<tr>"; echo "<td>" . $row['id'] . "</td>"; echo "<td>" . $row['first_name'] . "</td>"; echo "<td>" . $row['last_name'] . "</td>";

Page 31: PHP CURD EXAMPLE - WordPress.com · 2020. 4. 4. · PHP CURD EXAMPLE  TABLE OF CONTENTS 1) simple example of curd ..... 2 i. Config.php ..... 2

31

echo "<td>" . $row['email'] . "</td>"; echo "</tr>"; } echo "</table>"; // Close result set mysqli_free_result($result); } else{ echo "No records matching your query were found."; } } else{ echo "ERROR: Could not able to execute $sql. " . mysqli_error($link); } // Close connection mysqli_close($link); ?>

After ordering the result, the result set will look something like this:

+----+------------+-----------+----------------------+

| id | first_name | last_name | email |

+----+------------+-----------+----------------------+

| 3 | Clark | Kent | [email protected] |

| 5 | Harry | Potter | [email protected] |

| 2 | John | Rambo | [email protected] |

| 4 | John | Carter | [email protected] |

| 1 | Peter | Parker | [email protected] |

+----+------------+-----------+----------------------+

Tip: By default the ORDER BY clause sort the results in ascending order. If you want to sort the

records in a descending order, you can use the DESC keyword.

XIV. UPDATING DATABASE TABLE DATA

The UPDATE statement is used to change or modify the existing records in a database table.

This statement is typically used in conjugation with the WHERE clause to apply the changes to

only those records that matches specific criteria.

The basic syntax of the UPDATE statement can be given with:

UPDATE table_name SET column1=value, column2=value2,... WHERE column_name=some_value

Let's make a SQL query using the UPDATE statement and WHERE clause, after that we will

execute this query through passing it to the PHP mysqli_query() function to update the

tables records. Consider the following persons table inside the demo database:

Page 32: PHP CURD EXAMPLE - WordPress.com · 2020. 4. 4. · PHP CURD EXAMPLE  TABLE OF CONTENTS 1) simple example of curd ..... 2 i. Config.php ..... 2

32

+----+------------+-----------+----------------------+

| id | first_name | last_name | email |

+----+------------+-----------+----------------------+

| 1 | Peter | Parker | [email protected] |

| 2 | John | Rambo | [email protected] |

| 3 | Clark | Kent | [email protected] |

| 4 | John | Carter | [email protected] |

| 5 | Harry | Potter | [email protected] |

+----+------------+-----------+----------------------+

The PHP code in the following example will update the email address of a person in the

persons table whose id is equal to 1.

Example

Procedural Object Oriented PDO

Download <?php /* Attempt MySQL server connection. Assuming you are running MySQL server with default setting (user 'root' with no password) */ $link = mysqli_connect("localhost", "root", "", "demo"); // Check connection if($link === false){ die("ERROR: Could not connect. " . mysqli_connect_error()); } // Attempt update query execution $sql = "UPDATE persons SET email='[email protected]' WHERE id=1"; if(mysqli_query($link, $sql)){ echo "Records were updated successfully."; } else { echo "ERROR: Could not able to execute $sql. " . mysqli_error($link); } // Close connection mysqli_close($link); ?>

After update the persons table will look something like this:

+----+------------+-----------+--------------------------+

| id | first_name | last_name | email |

+----+------------+-----------+--------------------------+

| 1 | Peter | Parker | [email protected] |

Page 33: PHP CURD EXAMPLE - WordPress.com · 2020. 4. 4. · PHP CURD EXAMPLE  TABLE OF CONTENTS 1) simple example of curd ..... 2 i. Config.php ..... 2

33

| 2 | John | Rambo | [email protected] |

| 3 | Clark | Kent | [email protected] |

| 4 | John | Carter | [email protected] |

| 5 | Harry | Potter | [email protected] |

+----+------------+-----------+--------------------------+

Warning: The WHERE clause in the UPDATE statement specifies which record or records should

be updated. If you omit the WHERE clause, all records will be updated.

XV. DELETING DATABASE TABLE DATA Just as you insert records into tables, you can delete records from a table using the

SQL DELETE statement. It is typically used in conjugation with the WHERE clause to delete only

those records that matches specific criteria or condition.

The basic syntax of the DELETE statement can be given with:

DELETE FROM table_name WHERE column_name=some_value

Let's make a SQL query using the DELETE statement and WHERE clause, after that we will

execute this query through passing it to the PHP mysqli_query() function to delete the

tables records. Consider the following persons table inside the demo database:

+----+------------+-----------+----------------------+

| id | first_name | last_name | email |

+----+------------+-----------+----------------------+

| 1 | Peter | Parker | [email protected] |

| 2 | John | Rambo | [email protected] |

| 3 | Clark | Kent | [email protected] |

| 4 | John | Carter | [email protected] |

| 5 | Harry | Potter | [email protected] |

+----+------------+-----------+----------------------+

The PHP code in the following example will delete the records of those persons from

the persons table whose first_name is equal to John.

Example

Procedural Object Oriented PDO

Download <?php

Page 34: PHP CURD EXAMPLE - WordPress.com · 2020. 4. 4. · PHP CURD EXAMPLE  TABLE OF CONTENTS 1) simple example of curd ..... 2 i. Config.php ..... 2

34

/* Attempt MySQL server connection. Assuming you are running MySQL server with default setting (user 'root' with no password) */ $link = mysqli_connect("localhost", "root", "", "demo"); // Check connection if($link === false){ die("ERROR: Could not connect. " . mysqli_connect_error()); } // Attempt delete query execution $sql = "DELETE FROM persons WHERE first_name='John'"; if(mysqli_query($link, $sql)){ echo "Records were deleted successfully."; } else{ echo "ERROR: Could not able to execute $sql. " . mysqli_error($link); } // Close connection mysqli_close($link); ?>

After the deletion the persons table will look something like this:

+----+------------+-----------+----------------------+

| id | first_name | last_name | email |

+----+------------+-----------+----------------------+

| 1 | Peter | Parker | [email protected] |

| 3 | Clark | Kent | [email protected] |

| 5 | Harry | Potter | [email protected] |

+----+------------+-----------+----------------------+

As you can see the records has been deleted successfully from the persons table.

Warning: The WHERE clause in the DELETE statement specifies which record or records should

be deleted. If you omit the WHERE clause, all records will be deleted.