PHP Database
PHP Database
PHP Database
PHP's MYSQLi class has over 60 built-in functions to meet all the MySQL interfacing needs,
but to the meet our syllabus requirements, we shall use only the following functions:
Function Description
mysqli_connect() Opens a new connection to the MySQL server
mysqli_close() Closes a previously opened database connection
mysqli_error() Returns the last error description for the most recent function call
1
mysqli_query() Performs a query against the database
mysqli_select_db() Changes the default database for the connection
mysqli_num_rows() Returns the number of rows in a result set
mysqli_fetch_assoc() Fetches a result row as an associative array
Returns the number of affected rows in the previous MySQL
mysqli_affected_rows()
operation
Returns the last error message string from the last call
mysqli_connect_error()
to mysqli_connect().
Some other functions of MYSQLi class which you can use here are:
mysqli_errno() Returns the last error code for the most recent function call
Fetches all result rows as an associative array, a numeric
mysqli_fetch_all()
array, or both
Fetches a result row as an associative, a numeric array, or
mysqli_fetch_array()
both
Fetches one row from a result-set and returns it as an
mysqli_fetch_row()
enumerated array
mysqli_free_result() Frees the memory associated with a result
Escapes special characters in a string for use in an SQL
mysqli_real_escape_string()
statement
Where,
Argument Description
server An optional parameter that contains the server or host name running the
database server. If this is not specified then the default value is
localhost:3306.
password An optional parameter used to specify the password of the user accessing
the database. If it is not specified then default is an empty password.
2
PHP provides mysqli_close() function to close a database. Although any open connection is
automatically closed when script ends, it is always a good practice to close the database
when the use of database is over.
Syntax:
mysqli_close($dbhandle);
If no resource is specified in the parameter then the last opened database is closed.
Example:
<?php
$servername = "localhost";
$username = "root";
$pwd = "";
$conn = mysqli_connect($servername,$username, $pwd);
if (!$conn)
die("Could not connect".mysqli_error());
echo "Connected Successfully";
mysqli_close($conn);
?>
This code will try to connect PHP code to MySQL. If the connection is set, it will display the
message "Connected Successfully". If the connection could not be set due to any reason,
then it will give the message "Could not connect" followed by error description. In this case,
due to die() function, further execution of the PHP code will stop. Once the connection is set,
the code can do any kind of processing with MySQL databases.
mysqli_query():
The mysqli_query() function is a "catch all" function that can run about any MySQL query that
is given to it. It can be used to create and destroy a database and tables, insert data, delete
data, update data, and extract data from the database. This function takes two parameters
(connection and sql) and returns TRUE on success and FALSE on failure.
Syntax:
mysqli_query(connection, sql);
Where,
Argument Description
Creating a database:
A database can be created using mysqli_query() function with suitable query. Example:
3
<?php
$servername = "localhost";
$username = "root";
$pwd = "faipskwt";
if (!$conn)
if (mysqli_query($conn, $sql ))
else
mysqli_close($conn);
?>
This code will first set a connection with MySQL. If the connection is set, then it will try to
create a database with the name Library. If the database is created, it will give the message
"Database created successfully". If the database could not be created due to any reason,
then it will give the message "database not created" followed by the error description.
Selecting a database:
In case we want to use an already exising database, we can use the mysqli_select_db()
function. It is important to select a database as there may be multiple databases residing on
a server but in PHP a single connection can be linked to a single database at a time.
The function mysqli_select_db() returns TRUE on success and FALSE on failure.
Syntax:
mysqli_select_db(connection, databasename);
Example:
<?php
$servername = "localhost";
$username = "root";
4
$pwd = "faipskwt";
$conn = mysqli_connect($servername,$username, $pwd);
if (!$conn)
die("Could not connect".mysqli_error($conn));
echo "Connected Successfully<BR>";
if (mysqli_select_db($conn,"Library"))
echo "Database opened";
else echo "Could not open the database";
mysqli_close($conn);
?>
Alternatively, we can simply pass the database to be used as the fourth parameter to
mysqli_connect() function as shown in the following code:
<?php
$servername = "localhost";
$username = "root";
$pwd = "faipskwt";
$dbname = "Library";
$conn = mysqli_connect($servername,$username, $pwd,$dbname);
if (!$conn)
{
die("Could not connect".mysqli_error($conn));
}
echo "Connected Successfully<BR>";
mysqli_close($conn);
?>
<?php
$servername = "localhost";
$username = "root";
$pwd = "faipskwt";
$db = "Library";
$conn = mysqli_connect($servername,$username, $pwd, $db);
if (!$conn)
die("Could not connect to the database ".mysqli_error($conn));
$sql = "Create table BOOKS(Accno integer(5), Title varchar(30), ";
$sql .= "Author varchar(30), Publisher varchar(10), ";
$sql .= "Edition int(4), Price Decimal(7,2))";
if (mysqli_query($conn, $sql))
echo "Table created";
5
else echo "Table could not be created ".mysqli_error($conn);
mysqli_close($conn);
?>
Let us now write code to insert first record in the table BOOKS:
<?php
//PHP8-Example6
$servername = "localhost";
$username = "root";
$pwd = "faipskwt";
$db = "Library";
$conn = mysqli_connect($servername,$username, $pwd, $db);
if (!$conn)
die("Could not connect".mysqli_error($conn));
<?php
//PHP8-Example7
$servername = "localhost";
$username = "root";
$pwd = "faipskwt";
$db = "Library";
6
$conn = mysqli_connect($servername,$username, $pwd, $db);
if (!$conn)
$rows = mysqli_num_rows($res);
if ($rows > 0)
mysqli_close($conn);
?>
<?php
//PHP8-Example8
$servername = "localhost";
$username = "root";
7
$pwd = "faipskwt";
$db = "Library";
if (!$conn)
$sql = "Update Books set Price = Price + 20 where Price < 150";
if (mysqli_query($conn, $sql))
$rows = mysqli_affected_rows($conn);
if ($rows > 0)
mysqli_close($conn);
?>
Data can be deleted from a table using the DELETE command of SQL. Following is an
example to delete all the records from table BOOKS whose edition is earlier than 2006:
<?php
//PHP8-Example9
$servername = "localhost";
$username = "root";
$pwd = "faipskwt";
$db = "Library";
8
$conn = mysqli_connect($servername,$username, $pwd, $db);
if (!$conn)
if (mysqli_query($conn, $sql))
$rows = mysqli_affected_rows($conn);
if ($rows > 0)
mysqli_close($conn);
?>
Let us look at another example to delete a record but by asking the user to enter the
accession number of the book to be deleted using a form:
<html>
<body>
<?php
if (isset($_POST['delete']))
$servername = "localhost";
$username = "root";
$pwd = "faipskwt";
9
$db = "Library";
$aNum = $_POST['AccNum'];
if (!$conn)
if (mysqli_query($conn, $sql))
if (mysqli_affected_rows($conn)>0)
mysqli_close($conn);
else
?>
<tr>
</tr>
10
<tr>
<td></td>
<tr>
</table>
</form>
<?php
?>
</body>
</html>
11
EXERCISE
1. What is the advantage of using a database to store data over the other methods of
storing data in PHP?
2. What does the mysql_connect() function do? Explain with an example.
3. Which function can be used to diagnose and display information about a MySQL
connection error?
4. Why is it important to close and release the connection after use? Give the command
used to close it.
5. How can we execute SQL commands inside PHP code?
6. Which function can be used to select an already existing database?
7. Write the syntax for the CREATE TABLE command in SQL.
8. Which are the main data types which can be used in MySQL tables?
9. Why is the mysqli_affected_rows() function used?
10. Create a table called Teacher inside the School database in MySQL according to the
details given below:
Field Name Data Type Description
T_Code Auto Number Primary Key
T_Name Text Teachers Name
Designation Text Teachers Designation
DOB Date Date of Birth
Address Text Residential address
Basic_Sal Number Basic Salary
Qualification Text Educational Qualification
12
13