Chap 6-Php Mysql
Chap 6-Php Mysql
MySQL is the most popular database system used with PHP. With PHP, you can connect to
and manipulate databases.
What is MySQL?
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
We can query a database for specific information and have a recordset returned.
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
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).
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.
<?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
Use the PHP mysqli_connect() function to open a new connection to the MySQL server.
Before we can access data in a database, we must open a connection to the MySQL server.
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();
}
?>
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);
?>
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:
Create a Database
We must add the CREATE DATABASE statement to the mysqli_query() function to execute
the command.
<?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);
}
?>
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.
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.
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.
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);
?>
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)";
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.
The INSERT INTO statement is used to add new records to a database table.
Syntax
The first form doesn't specify the column names where the data will be inserted, only their values:
The second form specifies both the column names and the values to be inserted:
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();
}
8
VALUES ('Glenn', 'Quagmire',33)");
mysqli_close($con);
?>
Now we will create an HTML form that can be used to add new records to the "Persons" table.
<html>
<body>
</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.
<?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();
}
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’];
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>
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();
}
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’]).
Peter Griffin
Glenn Quagmire
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.
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);
?>
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.
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.
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();
}
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);
?>
Firstname Lastname
Glenn Quagmire
Peter Griffin
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();
}
17
WHERE FirstName='Peter'");
while($row = mysqli_fetch_array($result))
{
echo $row[‘FirstName’] . ” ” . $row[‘LastName’];
echo "<br>";
}
?>
Peter Griffin
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();
}
while($row = mysqli_fetch_array($result))
{
echo $row[‘FirstName’];
echo " " . $row[‘LastName’];
echo " " . $row[‘Age’];
echo "<br>";
}
18
mysqli_close($con);
?>
Glenn Quagmire 33
Peter Griffin 35
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
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:
Glen Quagmire 33
<?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_close($con);
?>
After the update, the "Persons" table will look like this:
Glen Quagmire 33
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.
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_close($con);
?>
Glenn Quagmire 33
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.
<html>
<head>
<title>Paging Using PHP</title>
</head>
<body>
<?php
$dbhost = 'localhost:3036';
$dbuser = 'root';
$dbpass = 'rootpassword';
$rec_limit = 10;
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);
22
}
else if( $left_rec < $rec_limit )
{
$last = $page – 2;
echo "<a href=\"$_PHP_SELF?page=$last\">Last 10 Records</a>";
}
mysql_close($conn);
?>
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.
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);
?>
MySQL provides one utility mysqldump to perform database backup. Using this binary, you can take
complete database dump in a single command.
system($command);
?>
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