PHP ─ PHP and MySQLPHP will work with virtually all database software, including Oracle and Sybase but most commonly used is freely available MySQL database. What you should already have?
Opening a Database Connection PHP provides mysql_connect function to open a database connection. This function takes five parameters and returns a MySQL link identifier on success, or FALSE on failure. Syntax
connection mysql_connect(server,user,passwd,new_link,client_flag);
Closing Database Connection Its simplest function mysql_close PHP provides to close a database connection. This function takes connection resource returned by mysql_connect function. It returns TRUE on success or FALSE on failure. Syntax
bool mysql_close ( resource $link_identifier );
If a resource is not specified, then the last opened database is closed. Example Try the following example to open and close a database connection −
<?php
$dbhost = 'localhost:3036'; $dbuser = 'guest'; $dbpass = 'guest123'; $conn = mysql_connect($dbhost, $dbuser, $dbpass); if(! $conn ) { die('Could not connect: ' . mysql_error()); } echo 'Connected successfully'; mysql_close($conn); ?> Create MySQL Database Using PHP Creating a Database To create and delete a database, you should have admin privilege. 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. Syntax
bool mysql_query( sql, connection );
Try the following example to create a database −
<?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 Database test_db'; $retval = mysql_query( $sql, $conn ); if(! $retval ) { die('Could not create database: ' . mysql_error()); } echo "Database test_db created successfully\n"; mysql_close($conn); ?> Selecting a Database Once you establish a connection with a database server, then it is required to select a particular database with which all your tables are associated. This is required because there may be multiple databases residing on a single server and you can do work with a single database at a time. PHP provides function mysql_select_db to select a database. It returns TRUE on success or FALSE on failure. Syntax
bool mysql_select_db( db_name, connection );
Here is the example showing you how to select a database.
<?php
$dbhost = 'localhost:3036'; $dbuser = 'guest'; $dbpass = 'guest123'; $conn = mysql_connect($dbhost, $dbuser, $dbpass); if(! $conn ) { die('Could not connect: ' . mysql_error()); } echo 'Connected successfully'; mysql_select_db( 'test_db' ); mysql_close($conn); ?> 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. Example Try the 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); ?> In case you need to create many tables, then it’s 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 execute 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); ?> Delete MySQL Database Using PHP Deleting a Database If a database is no longer required, then it can be deleted forever. You can use pass an SQL command to mysql_query to delete a database. Example Try the following example to drop a database.
<?php
$dbhost = 'localhost:3036'; $dbuser = 'root'; $dbpass = 'rootpassword'; $conn = mysql_connect($dbhost, $dbuser, $dbpass); if(! $conn ) { die('Could not connect: ' . mysql_error()); } $sql = 'DROP DATABASE test_db'; $retval = mysql_query( $sql, $conn ); if(! $retval ) { die('Could not delete database db_test: ' . mysql_error()); } echo "Database deleted successfully\n"; mysql_close($conn); ?> WARNING – It’s very dangerous to delete a database and any table. So before deleting any table or database you should make sure you are doing everything intentionally. Deleting a Table It’s again a matter of issuing one SQL command through mysql_query function to delete any database table. But be very careful while using this command because by doing so you can delete some important information you have in your table. Example Try the following example to drop a table −
<?php
$dbhost = 'localhost:3036'; $dbuser = 'root'; $dbpass = 'rootpassword'; $conn = mysql_connect($dbhost, $dbuser, $dbpass); if(! $conn ) { die('Could not connect: ' . mysql_error()); } $sql = 'DROP TABLE employee'; $retval = mysql_query( $sql, $conn ); if(! $retval ) { die('Could not delete table employee: ' . mysql_error()); } echo "Table deleted successfully\n"; mysql_close($conn); ?> Insert Data to MySQL Database Data can be entered into MySQL tables by executing SQL INSERT statement through PHP function mysql_query. Below a simple example to insert a record into employee table. Example Try the 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 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> <?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> <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> Retrieving Data from MySQL Database 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. Following is a simple example to fetch records from employee table. Example Try the 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 ) { 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 content 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 the 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 the 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> ". "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 the 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 the same result. Releasing Memory It is 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 the following example.
<?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. The procedure will remain the same as mentioned above. Using Paging through PHP It’s 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. Following is a simple example to fetch records using LIMIT clause to generate paging. Example Try the 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()); } 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>"; }else if( $left_rec < $rec_limit ) { $last = $page - 2; echo "<a href = \"$_PHP_SELF?page = $last\">Last 10 Records</a>"; } mysql_close($conn); ?> </body> </html> Updating Data into MySQL Database Data can be updated into MySQL tables by executing SQL UPDATE statement through PHP function mysql_query. Below is a simple example to update records into employee table. To update a record in any table it is required to locate that record by using a conditional clause. Below example uses primary key to match a record in employee table. Example Try the following example to understand update operation. You need to provide an employee ID to update an employee salary.
<html>
<head> <title>Update a Record in MySQL Database</title> </head> <body> <?php if(isset($_POST['update'])) { $dbhost = 'localhost:3036'; $dbuser = 'root'; $dbpass = 'rootpassword'; $conn = mysql_connect($dbhost, $dbuser, $dbpass); if(! $conn ) { die('Could not connect: ' . mysql_error()); } $emp_id = $_POST['emp_id']; $emp_salary = $_POST['emp_salary']; $sql = "UPDATE employee ". "SET emp_salary = $emp_salary ". "WHERE emp_id = $emp_id" ; mysql_select_db('test_db'); $retval = mysql_query( $sql, $conn ); if(! $retval ) { die('Could not update data: ' . mysql_error()); } echo "Updated 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 ID</td> <td><input name = "emp_id" type = "text" id = "emp_id"></td> </tr> <tr> <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 = "update" type = "submit" id = "update" value = "Update"> </td> </tr> </table> </form> <?php } ?> </body> </html> Deleting Data from MySQL Database Data can be deleted from MySQL tables by executing SQL DELETE statement through PHP function mysql_query. Following is a simple example to delete records into employee table. To delete a record in any table it is required to locate that record by using a conditional clause. Below example uses primary key to match a record in employee table. Example Try the following example to understand delete operation. You need to provide an employee ID to delete an employee record from employee table.
<html>
<head> <title>Delete a Record from MySQL Database</title> </head> <body> <?php if(isset($_POST['delete'])) { $dbhost = 'localhost:3036'; $dbuser = 'root'; $dbpass = 'rootpassword'; $conn = mysql_connect($dbhost, $dbuser, $dbpass); if(! $conn ) { die('Could not connect: ' . mysql_error()); } $emp_id = $_POST['emp_id']; $sql = "DELETE employee ". "WHERE emp_id = $emp_id" ; mysql_select_db('test_db'); $retval = mysql_query( $sql, $conn ); if(! $retval ) { die('Could not delete data: ' . mysql_error()); } echo "Deleted 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 ID</td> <td><input name = "emp_id" type = "text" id = "emp_id"></td> </tr> <tr> <td width = "100"> </td> <td> </td> </tr> <tr> <td width = "100"> </td> <td> <input name = "delete" type = "submit" id = "delete" value = "Delete"> </td> </tr> </table> </form> <?php } ?> </body> </html> Using PHP to Backup MySQL Database It is always a 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 the 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"; 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 the 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 If you have phpMyAdmin user interface available, then it is 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. |