0% found this document useful (0 votes)
13 views

Chap 6-Php Mysql

b bcvvcv v

Uploaded by

nemeralelisa38
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views

Chap 6-Php Mysql

b bcvvcv v

Uploaded by

nemeralelisa38
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 25

CHAPTER 6: PHP and MySQL

MySQL is the most popular database system used with PHP. With PHP, you can connect to
and manipulate databases.

What is MySQL?

 MySQL is a database system used on the web


 MySQL is a database system that runs on a server
 MySQL is ideal for both small and large applications
 MySQL is very fast, reliable, and easy to use
 MySQL supports standard SQL
 MySQL compiles on a number of platforms
 MySQL is free to download and use
  MySQL is developed, distributed, and supported by Oracle Corporation
 MySQL is named after co-founder Monty Widenius's daughter: My

The data in MySQL is stored in tables. A table is a collection of related data, and it consists of
columns and rows.

Databases are useful when storing information categorically. A company may have a database with the
following tables:

 Employees
 Products
 Customers
 Orders

PHP + MySQL

 PHP combined with MySQL are cross-platform (you can develop in Windows and serve on
a Unix platform)

Queries

A query is a question or a request.

We can query a database for specific information and have a recordset returned.

Look at the following query (using standard SQL):

SELECT LastName FROM Employees

The query above selects all the data in the "LastName" column from the "Employees" table.

1
Download MySQL Database

If you don't have a PHP server with a MySQL Database, you can download MySQL for free here:
http://www.mysql.com

Facts About MySQL Database

One great thing about MySQL is that it can be scaled down to support embedded database
applications. Maybe it is because of this many people think that MySQL can only handle small and
medium-sized systems.

The truth is that MySQL is the de-facto standard database system for web sites with HUGE volumes
of both data and end users (like Friendster, Yahoo, and Google).

Look at http://www.mysql.com/customers/ for an overview of companies using MySQL.

Choosing an API

PHP offers three different APIs to connect to MySQL. Below we show the APIs provided by the mysql,
mysqli, and PDO extensions. Each code snippet creates a connection to a MySQL server running on
"example.com" using the username "user" and the password "password". And a query is run to greet the
user.

Example #1 Comparing the three MySQL APIs

<?php
// mysqli
$mysqli = new mysqli("example.com", "user", "password", "database");
$result = $mysqli->query("SELECT 'Hello, dear MySQL user!' AS _message FROM DUAL");
$row = $result->fetch_assoc();// to Fetch a result row as an associative array
echo htmlentities($row['_message']);// to Convert some characters to HTML entities

// PDO
$pdo = new PDO('mysql:host=example.com;dbname=database', 'user', 'password');
$statement = $pdo->query("SELECT 'Hello, dear MySQL user!' AS _message FROM DUAL");
$row = $statement->fetch(PDO::FETCH_ASSOC); echo htmlentities($row['_message']);

// mysql
$c = mysql_connect("example.com", "user", "password");
mysql_select_db("database");
$result = mysql_query("SELECT 'Hello, dear MySQL user!' AS _message FROM DUAL");
$row = mysql_fetch_assoc($result);
echo htmlentities($row['_message']);
?>

2
Recommended API

It is recommended to use either the mysqli or PDO_MySQL extensions. It is not recommended to use the
old mysql extension for new development, as it was deprecated in PHP 5.5.0 and was removed in PHP 7.
A detailed feature comparison matrix is provided below. The overall performance of all three extensions
is considered to be about the same. Although the performance of the extension contributes only a fraction
of the total run time of a PHP web request. Often, the impact is as low as 0.1%.

Feature comparison

ext/mysqli PDO_MySQL ext/mysql


PHP version introduced 5.0 5.1 2.0
Included with PHP 5.x Yes Yes Yes
Included with PHP 7.x Yes Yes No
Development status Active Active Maintenance only in 5.x;
removed in 7.x
Lifecycle Active Active Deprecated in 5.x; removed
in 7.x
Recommended for new projects Yes Yes No
OOP Interface Yes Yes No
Procedural Interface Yes No Yes
API supports non-blocking, asynchronous Yes No No
queries with mysqlnd
Persistent Connections Yes Yes Yes
API supports Charsets Yes Yes Yes
API supports server-side Prepared Yes Yes No
Statements
API supports client-side Prepared No Yes No
Statements
API supports Stored Procedures Yes Yes No
API supports Multiple Statements Yes Most No
API supports Transactions Yes Yes No
Transactions can be controlled with SQL Yes Yes Yes
Supports all MySQL 5.1+ functionality Yes Most No

PHP How Connect to the MySQL

Use the PHP mysqli_connect() function to open a new connection to the MySQL server.

Open a Connection to the MySQL Server:

Before we can access data in a database, we must open a connection to the MySQL server.

In PHP, this is done with the mysqli_connect() function.

Syntax

mysqli_connect(host,username,password,dbname);

3
Parameter Description
host Optional. Either a host name or an IP address
username Optional. The MySQL user name
password Optional. The password to log in with
dbname Optional. The default database to be used when performing queries

Note: There are more available parameters, but the ones listed above are the most important.

In the following example, we store the connection in a variable ($con) for later use in the script:

<?php
// Create connection
$con=mysqli_connect("example.com","peter","abc123","my_db");

// Check connection
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
?>

How Close a Connection

The connection will be closed automatically when the script ends. To close the connection before, use the
mysqli_close() function:

<?php
$con=mysqli_connect("example.com","peter","abc123","my_db");

// Check connection
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

mysqli_close($con);
?>

PHP Mysql Create Database and Tables

A database holds one or more tables. To create and delete a database you should have admin priviledge. It’s
very easy to create a new MySQL database. PHP uses mysql_query function to create a MySQL database.
This function takes two parameters and returns TRUE on success or FALSE on failure.

4
Syntax:

mysql_query( sql, connection );

Create a Database

We must add the CREATE DATABASE statement to the mysqli_query() function to execute
the command.

The following example creates a database named "my_db":

<?php
$con=mysqli_connect("example.com","peter","abc123");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

// Create database
$sql="CREATE DATABASE my_db";
if (mysqli_query($con,$sql))
{
echo "Database my_db created successfully";
}
else
{
echo "Error creating database: " . mysqli_error($con);
}
?>

Creating Database Tables:

To create tables in the new database you need to do the same thing as creating the database. First
create the SQL query to create the tables then execute the query using mysql_query() function.

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

We must add the CREATE TABLE statement to the mysqli_query() function to execute the command.

The following example creates a table named "Persons", with three columns. The column names will be
"FirstName", "LastName" and "Age":

<?php
$con=mysqli_connect("example.com","peter","abc123","my_db"); //
Check connection
if (mysqli_connect_errno())
{

5
echo "Failed to connect to MySQL: " .
mysqli_connect_error(); }

// Create table
$sql="CREATE TABLE persons(FirstName CHAR(30),LastName CHAR(30),Age
INT)";

// Execute query
if (mysqli_query($con,$sql))
{
echo "Table persons created successfully";
}
else
{
echo "Error creating table: " . mysqli_error($con);
}
?>

Note: When you create a database field of type CHAR, you must specify the maximum length of the
field, e.g. CHAR(50).The data type specifies what type of data the column can hold. For a complete
reference of all the data types available in MySQL, go to our complete Data Types reference.

Example 2: Try out following example to create a table:


<?php
$dbhost = 'localhost:3036';
$dbuser = 'root';
$dbpass = 'rootpassword';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{ die('Could not connect: ' . mysql_error());}
echo 'Connected successfully';
$sql = 'CREATE TABLE employee( '.
'emp_id INT NOT NULL AUTO_INCREMENT, '.
'emp_name VARCHAR(20) NOT NULL, '.
'emp_address VARCHAR(20) NOT NULL, '.
'emp_salary INT NOT NULL, '.
'join_date timestamp(14) NOT NULL, '.
'primary key ( emp_id ))';

mysql_select_db('test_db');
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not create table: ' . mysql_error());
}
echo "Table employee created successfully\n";
mysql_close($conn);
?>

6
In case you need to create many tables then its better to create a text file first and put all the SQL
commands in that text file and then load that file into $sql variable and excute those commands.

Consider the following content in sql_query.txt file

CREATE TABLE employee(


emp_id INT NOT NULL AUTO_INCREMENT,
emp_name VARCHAR(20) NOT NULL,
emp_address VARCHAR(20) NOT NULL,
emp_salary INT NOT NULL,
join_date timestamp(14) NOT NULL,
primary key ( emp_id ));
<?php
$dbhost = 'localhost:3036';
$dbuser = 'root';
$dbpass = 'rootpassword';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
$query_file = 'sql_query.txt';

$fp = fopen($query_file, 'r');


$sql = fread($fp, filesize($query_file));
fclose($fp);

mysql_select_db('test_db');
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not create table: ' . mysql_error());
}
echo "Table employee created successfully\n";
mysql_close($conn);
?>

Primary Keys and Auto Increment Fields

Each table in a database should have a primary key field.

A primary key is used to uniquely identify the rows in a table. Each primary key value must be unique
within the table. Furthermore, the primary key field cannot be null because the database engine requires
a value to locate the record.

The following example sets the PID field as the primary key field. The primary key field is often an ID
number, and is often used with the AUTO_INCREMENT setting. AUTO_INCREMENT automatically
increases the value of the field by 1 each time a new record is added. To ensure that the primary key field
cannot be null, we must add the NOT NULL setting to the field:

7
$sql = "CREATE TABLE Persons (PID INT NOT NULL AUTO_INCREMENT,
PRIMARY KEY(PID),FirstName CHAR(15),LastName CHAR(15),Age INT)";

PHP MySQL Insert Data

Data can be entered into MySQL tables by executing SQL INSERT statement through PHP
function mysql_query.The INSERT INTO statement is used to insert new records in a table.

Insert Data into a Database Table

The INSERT INTO statement is used to add new records to a database table.

Syntax

It is possible to write the INSERT INTO statement in two forms.

The first form doesn't specify the column names where the data will be inserted, only their values:

INSERT INTO table_nameVALUES (value1, value2, value3,…)

The second form specifies both the column names and the values to be inserted:

INSERT INTO table_name (column1, column2, column3,…)


VALUES (value1, value2, value3,…)

To learn more about SQL, please visit SQL tutorial.

To get PHP to execute the statements above we must use the mysqli_query() function. This function
is used to send a query or command to a MySQL connection.

Example: In the previous section, we created a table named "Persons", with three columns;
"FirstName", "LastName" and "Age". We will use the same table in this example. The following example
adds two new records to the "Persons" table:

<?php
$con=mysqli_connect("example.com","peter","abc123","my_db"); //
Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

mysqli_query($con,"INSERT INTO Persons (FirstName, LastName, Age)


VALUES ('Peter', 'Griffin',35)");

mysqli_query($con,"INSERT INTO Persons (FirstName, LastName, Age)

8
VALUES ('Glenn', 'Quagmire',33)");

mysqli_close($con);
?>

PHP Insert Data from a Form into a Database

Now we will create an HTML form that can be used to add new records to the "Persons" table.

Here is the HTML form:

<html>
<body>

<form action="insert.php" method="post">


Firstname: <input type="text" name="firstname">
Lastname: <input type="text" name="lastname">
Age: <input type="text" name="age">
<input type="submit">
</form>

</body>
</html>

When a user clicks the submit button in the HTML form in the example above, the form data is sent
to "insert.php".

The "insert.php" file connects to a database, and retrieves the values from the form with the PHP
$_POST variables.

Then, the mysqli_query() function executes the INSERT INTO statement, and a new record will be added
to the "Persons" table.

Here is the "insert.php" page:

<?php
$con=mysqli_connect("example.com","peter","abc123","my_db"); //
Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

$sql="INSERT INTO Persons (FirstName, LastName, Age)


VALUES
('$_POST[firstname]’,’$_POST[lastname]’,’$_POST[age]')";

if (!mysqli_query($con,$sql))

9
{
die('Error: ' . mysqli_error($con));
}
echo "1 record added";

mysqli_close($con);
?>

Example: Try out following example to insert record into employee table.

<?php
$dbhost = 'localhost:3036';
$dbuser = 'root';
$dbpass = 'rootpassword';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
$sql = 'INSERT INTO employee '.
'(emp_name,emp_address, emp_salary, join_date) '.
'VALUES ( "guest", "XYZ", 2000, NOW() )';

mysql_select_db('test_db');
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not enter data: ' . mysql_error());
}
echo "Entered data successfully\n";
mysql_close($conn);
?>

In real application, all the values will be taken using HTML form and then those values will be
captured using PHP script and finally they will be inserted into MySQL tables.

While doing data insert its best practice to use function get_magic_quotes_gpc() to check if current
configuration for magic quote is set or not. If this function returns false then use function addslashes()
to add slashes before quotes.

Example: Try out this example by putting this code into add_employee.php, this will take input using
HTML Form and then it will create records into database.

<html>
<head>
<title>Add New Record in MySQL Database</title>
</head>
<body>

10
<?php
if(isset($_POST[‘add’]))
{
$dbhost = 'localhost:3036';
$dbuser = 'root';
$dbpass = 'rootpassword';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}

if(! get_magic_quotes_gpc() )
{
$emp_name = addslashes ($_POST[’emp_name’]);
$emp_address = addslashes ($_POST[’emp_address’]);
}
else
{
$emp_name = $_POST[’emp_name’];
$emp_address = $_POST[’emp_address’];
}
$emp_salary = $_POST[’emp_salary’];

$sql = "INSERT INTO employee ".


"(emp_name,emp_address, emp_salary, join_date) ".
"VALUES('$emp_name','$emp_address',$emp_salary, NOW())";
mysql_select_db('test_db');
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not enter data: ' . mysql_error());
}
echo "Entered data successfully\n";
mysql_close($conn);
}
else
{
?>
<form method="post" action="<?php $_PHP_SELF ?>">
<table width="400" border="0" cellspacing="1"
cellpadding="2"> <tr>
<td width="100">Employee Name</td>
<td><input name="emp_name" type="text" id="emp_name"></td>
</tr>
<tr>
<td width="100">Employee Address</td>
<td><input name="emp_address" type="text" id="emp_address"></td>
</tr>
<tr>

11
<td width="100">Employee Salary</td>
<td><input name="emp_salary" type="text" id="emp_salary"></td>
</tr>
<tr>
<td width="100"> </td>
<td> </td>
</tr>
<tr>
<td width="100"> </td>
<td>
<input name="add" type="submit" id="add" value="Add Employee">
</td>
</tr>
</table>
</form>
<?php
}
?>
</body>
</html>

PHP MySQL Select

The SELECT statement is used to select data from a database.

Select Data From a Database Table

The SELECT statement is used to select data from a database.

Syntax

SELECT column_name(s)
FROM table_name

To get PHP to execute the statement above we must use the mysqli_query() function. This function is
used to send a query or command to a MySQL connection.

Data can be fetched from MySQL tables by executing SQL SELECT statement through PHP
function mysql_query. You have several options to fetch data from MySQL.

The most frequently used option is to use function mysql_fetch_array(). This function returns row as an
associative array, a numeric array, or both. This function returns FALSE if there are no more rows.

The following example selects all the data stored in the "Persons" table (The * character selects all the
data in the table):

<?php
$con=mysqli_connect("example.com","peter","abc123","my_db");

12
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

$result = mysqli_query($con,"SELECT * FROM Persons");

while($row = mysqli_fetch_array($result))
{
echo $row[‘FirstName’] . ” ” . $row[‘LastName’];
echo "<br>";
}

mysqli_close($con);
?>

The example above stores the data returned by the mysqli_query() function in the $result variable.

Next, we use the mysqli_fetch_array() function to return the first row from the recordset as an array.
Each call to mysqli_fetch_array() returns the next row in the recordset. The while loop loops through all
the records in the recordset. To print the value of each row, we use the PHP $row variable
($row[‘FirstName’] and $row[‘LastName’]).

The output of the code above will be:

Peter Griffin
Glenn Quagmire

Below is a simple example to fetch records from employee table.

Example: Try out following example to display all the records from employee table.

<?php
$dbhost = 'localhost:3036';
$dbuser = 'root';
$dbpass = 'rootpassword';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
$sql = 'SELECT emp_id, emp_name, emp_salary FROM employee';

mysql_select_db('test_db');
$retval = mysql_query( $sql, $conn );
if(! $retval )
{

13
die('Could not get data: ' . mysql_error());
}
while($row = mysql_fetch_array($retval, MYSQL_ASSOC))
{
echo "EMP ID :{$row[’emp_id’]} <br> ".
"EMP NAME : {$row[’emp_name’]} <br> ".
"EMP SALARY : {$row[’emp_salary’]} <br> ".
"——————————–<br>";
}
echo "Fetched data successfully\n";
mysql_close($conn);
?>

The contents of the rows are assigned to the variable $row and the values in row are then printed.

NOTE: Always remember to put curly brackets when you want to insert an array value directly into a
string.

In above example the constant MYSQL_ASSOC is used as the second argument to


mysql_fetch_array(), so that it returns the row as an associative array. With an associative array, you can
access the field by using their name instead of using the index.

PHP provides another function called mysql_fetch_assoc() which also returns the row as an
associative array.

Example: Try out following example to display all the records from employee table using
mysql_fetch_assoc() function.

<?php
$dbhost = 'localhost:3036';
$dbuser = 'root';
$dbpass = 'rootpassword';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
$sql = 'SELECT emp_id, emp_name, emp_salary FROM employee';

mysql_select_db('test_db');
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not get data: ' . mysql_error());
}
while($row = mysql_fetch_assoc($retval))
{
echo "EMP ID :{$row[’emp_id’]} <br> ".
"EMP NAME : {$row[’emp_name’]} <br> ".

14
"EMP SALARY : {$row[’emp_salary’]} <br> ".
"——————————–<br>";
}
echo "Fetched data successfully\n";
mysql_close($conn);
?>

You can also use the constant MYSQL_NUM, as the second argument to mysql_fetch_array(). This will
cause the function to return an array with numeric index.

Example: Try out following example to display all the records from employee table using
MYSQL_NUM argument.

<?php
$dbhost = 'localhost:3036';
$dbuser = 'root';
$dbpass = 'rootpassword';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
$sql = 'SELECT emp_id, emp_name, emp_salary FROM employee';

mysql_select_db('test_db');
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not get data: ' . mysql_error());
}
while($row = mysql_fetch_array($retval, MYSQL_NUM))
{
echo "EMP ID :{$row[0]} <br> ".
"EMP NAME : {$row[1]} <br> ".
"EMP SALARY : {$row[2]} <br> ".
"——————————–<br>";
}
echo "Fetched data successfully\n";
mysql_close($conn);
?>

All the above three examples will produce same result.

Releasing Memory:

It’s a good practice to release cursor memory at the end of each SELECT statement. This can be done
by using PHP function mysql_free_result(). Below is the example to show how it has to be used.

Example: Try out following example

15
<?php
$dbhost = 'localhost:3036';
$dbuser = 'root';
$dbpass = 'rootpassword';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
$sql = 'SELECT emp_id, emp_name, emp_salary FROM employee';

mysql_select_db('test_db');
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not get data: ' . mysql_error());
}
while($row = mysql_fetch_array($retval, MYSQL_NUM))
{
echo "EMP ID :{$row[0]} <br> ".
"EMP NAME : {$row[1]} <br> ".
"EMP SALARY : {$row[2]} <br> ".
"——————————–<br>";
}
mysql_free_result($retval);
echo "Fetched data successfully\n";
mysql_close($conn);
?>

While fetching data, you can write as complex SQL as you like. Procedure will remain same
as mentioned above.

Display the Result in an HTML Table

The following example selects the same data as the example above, but will display the data in an HTML
table:

<?php
$con=mysqli_connect("example.com","peter","abc123","my_db"); //
Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

$result = mysqli_query($con,"SELECT * FROM Persons");

echo "<table border='1'>


<tr>

16
<th>Firstname</th>
<th>Lastname</th>
</tr>";

while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row[‘FirstName’] . "</td>";
echo "<td>" . $row[‘LastName’] . "</td>";
echo "</tr>";
}
echo "</table>";

mysqli_close($con);
?>

The output of the code above will be:

Firstname Lastname
Glenn Quagmire
Peter Griffin

PHP MySQL Where

The WHERE clause is used to filter records.

The WHERE clause is used to extract only those records that fulfill a specified criterion.

Syntax

SELECT column_name(s)
FROM table_name
WHERE column_name operator value

To get PHP to execute the statement above we must use the mysqli_query() function. This function is
used to send a query or command to a MySQL connection.

Example: The following example selects all rows from the "Persons" table where "FirstName='Peter'":
<?php
$con=mysqli_connect("example.com","peter","abc123","my_db"); //
Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

$result = mysqli_query($con,"SELECT * FROM Persons

17
WHERE FirstName='Peter'");

while($row = mysqli_fetch_array($result))
{
echo $row[‘FirstName’] . ” ” . $row[‘LastName’];
echo "<br>";
}
?>

The output of the code above will be:

Peter Griffin

PHP MySQL Order By

The ORDER BY keyword is used to sort the data in a recordset.

The ORDER BY keyword sort the records in ascending order by default.

If you want to sort the records in a descending order, you can use the DESC keyword.

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

Example:The following example selects all the data stored in the "Persons" table, and sorts the result by
the "Age" column:

<?php
$con=mysqli_connect("example.com","peter","abc123","my_db"); //
Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

$result = mysqli_query($con,"SELECT * FROM Persons ORDER BY age");

while($row = mysqli_fetch_array($result))
{
echo $row[‘FirstName’];
echo " " . $row[‘LastName’];
echo " " . $row[‘Age’];
echo "<br>";
}

18
mysqli_close($con);
?>

The output of the code above will be:

Glenn Quagmire 33
Peter Griffin 35

Order by Two Columns

It is also possible to order by more than one column. When ordering by more than one column, the second
column is only used if the values in the first column are equal:

SELECT column_name(s)
FROM table_name
ORDER BY column1, column2

PHP MySQL Update Data

The UPDATE statement is used to update existing records in a table.

Update Data In a Database syntax:

UPDATE table_name
SET column1=value, column2=value2,…
WHERE some_column=some_value

Note: Notice the WHERE clause in the UPDATE syntax. The WHERE clause specifies which record
or records that should be updated. If you omit the WHERE clause, all records will be updated!

To get PHP to execute the statement above we must use the mysqli_query() function. This function is
used to send a query or command to a MySQL connection.

Example

Earlier in the tutorial we created a table named "Persons". Here is how it looks:

FirstName LastName Age


Peter Griffin 35

Glen Quagmire 33

The following example updates some data in the "Persons" table:

<?php

19
$con=mysqli_connect("example.com","peter","abc123","my_db"); //
Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

mysqli_query($con,"UPDATE Persons SET Age=36


WHERE FirstName='Peter' AND LastName='Griffin'");

mysqli_close($con);
?>

After the update, the "Persons" table will look like this:

FirstName LastName Age


Peter Griffin 36

Glen Quagmire 33

PHP MySQL Delete Data

The DELETE FROM statement is used to delete records from a database table.

Syntax
DELETE FROM table_name
WHERE some_column = some_value

Note: Notice the WHERE clause in the DELETE syntax. The WHERE clause specifies which record or
records that should be deleted. If you omit the WHERE clause, all records will be deleted!

To get PHP to execute the statement above we must use the mysqli_query() function. This function is
used to send a query or command to a MySQL connection.

Example: Look at the following "Persons" table:

FirstName LastName Age

Peter Griffin 35

Glenn Quagmire 33

The following example deletes all the records in the "Persons" table where LastName='Griffin':

<?php
$con=mysqli_connect("example.com","peter","abc123","my_db");

20
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

mysqli_query($con,"DELETE FROM Persons WHERE LastName='Griffin'");

mysqli_close($con);
?>

After the deletion, the table will look like this:

FirstName LastName Age

Glenn Quagmire 33

PHP MySQL Creating Paging

It is always possible that your SQL SELECT statement query may result into thousands of records. But
it is not good idea to display all the results on one page. So, we can divide this result into many pages as
per requirement.

Paging means showing your query result in multiple pages instead of just put them all in one long page.

MySQL helps to generate paging by using LIMIT clause which will take two arguments. First
argument as OFFSET and second argument how many records should be returned from the database.

Below is a simple example to fetch records using LIMIT clause to generate paging.

Example: Try out following example to display 10 records per page.

<html>
<head>
<title>Paging Using PHP</title>
</head>
<body>
<?php
$dbhost = 'localhost:3036';
$dbuser = 'root';
$dbpass = 'rootpassword';
$rec_limit = 10;

$conn = mysql_connect($dbhost, $dbuser, $dbpass);


if(! $conn )
{
die('Could not connect: ' . mysql_error());

21
}
mysql_select_db('test_db');
/* Get total number of records */
$sql = "SELECT count(emp_id) FROM employee ";
$retval = mysql_query( $sql, $conn ); if(! $retval )

{
die('Could not get data: ' . mysql_error());
}
$row = mysql_fetch_array($retval, MYSQL_NUM );
$rec_count = $row[0];

if( isset($_GET{'page'} ) )
{
$page = $_GET{'page'} + 1;
$offset = $rec_limit * $page ;
}
else
{
$page = 0;
$offset = 0;
}
$left_rec = $rec_count – ($page * $rec_limit);

$sql = "SELECT emp_id, emp_name, emp_salary ".


"FROM employee ".
"LIMIT $offset, $rec_limit";

$retval = mysql_query( $sql, $conn );


if(! $retval )
{
die('Could not get data: ' . mysql_error());
}
while($row = mysql_fetch_array($retval, MYSQL_ASSOC))
{
echo "EMP ID :{$row[’emp_id’]} <br> ".
"EMP NAME : {$row[’emp_name’]} <br> ".
"EMP SALARY : {$row[’emp_salary’]} <br> ".
"——————————–<br>";
}

if( $page > 0 )


{
$last = $page – 2;
echo "<a href=\"$_PHP_SELF?page=$last\">Last 10 Records</a> |";
echo "<a href=\"$_PHP_SELF?page=$page\">Next 10 Records</a>";
}
else if( $page == 0 )
{
echo "<a href=\"$_PHP_SELF?page=$page\">Next 10 Records</a>";

22
}
else if( $left_rec < $rec_limit )
{
$last = $page – 2;
echo "<a href=\"$_PHP_SELF?page=$last\">Last 10 Records</a>";
}
mysql_close($conn);
?>

PHP mysql backup

Perform MySQL backup using PHP

It is always good practice to take a regular backup of your database. There are three ways you can use to
take backup of your MySQL database.

 Using SQL Command through PHP.


 Using MySQL binary mysqldump through PHP.
 Using phpMyAdmin user interface.

Using SQL Command through PHP

You can execute SQL SELECT command to take a backup of any table. To take a complete database
dump you will need to write separate query for separate table. Each table will be stored into separate
text file.

Example: Try out following example of using SELECT INTO OUTFILE query for creating
table backup:

<?php
$dbhost = 'localhost:3036';
$dbuser = 'root';
$dbpass = 'rootpassword';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
$table_name = "employee";
$backup_file = "/tmp/employee.sql";
$sql = "SELECT * INTO OUTFILE '$backup_file' FROM $table_name";

mysql_select_db('test_db');
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not take data backup: ' . mysql_error());
}
echo "Backedup data successfully\n";

23
mysql_close($conn);
?>

There may be instances when you would need to restore data which you have backed up some time ago.
To restore the backup you just need to run LOAD DATA INFILE query like this :

<?php
$dbhost = 'localhost:3036';
$dbuser = 'root';
$dbpass = 'rootpassword';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
$table_name = "employee";
$backup_file = "/tmp/employee.sql";
$sql = "LOAD DATA INFILE '$backup_file' INTO TABLE $table_name";

mysql_select_db('test_db');
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not load data : ' . mysql_error());
}
echo "Loaded data successfully\n";
mysql_close($conn);
?>

Using MySQL binary mysqldump through PHP:

MySQL provides one utility mysqldump to perform database backup. Using this binary, you can take
complete database dump in a single command.

Example:Try out following example to take your complete database dump:


<?php
$dbhost = 'localhost:3036';
$dbuser = 'root';
$dbpass = 'rootpassword';

$backup_file = $dbname . date("Y-m-d-H-i-s") . '.gz';


$command = "mysqldump –opt -h $dbhost -u $dbuser -p $dbpass ".
"test_db | gzip > $backup_file";

system($command);
?>

Using phpMyAdmin user interface:

24
If you have phpMyAdmin user interface available, then it’s very easy for you to take backup of your
database.

To back up your MySQL database using phpMyAdmin click on the "export" link on phpMyAdmin main
page. Choose the database you wish to backup, check the appropriate SQL options and enter the name
for the backup file.

25

You might also like