Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
71 views13 pages

PHP Database

Download as docx, pdf, or txt
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 13

Server Side Scripting

PHP-8: Working with Databases


Let us recall the following terms regarding databases that we have already learnt:
Database is an organized collection of data to serve multiple applications.
Database management system (DBMS) is a software that efficiently stores, retrieves, and
manages databases.
Relational Database is a database in which the data is organized in the form of relations
(also called tables). The relations of a database are generally related to one another.
RDBMS (Relational Database Management System) is a software that lets us create,
update, and administer relational databases. Some very popular RDBMS are: MySQL,
Oracle, MS SQL Server, IBMs DB2.
Table is a collection of data of similar entities (objects like students, books, tickets etc.) in the
form of rows and columns.
Fields are different columns within a table and are the smallest unit of named data.
Records are the rows of a table and are a collection of data items or fields.
Primary key is an attribute or a set of attributes that uniquely identifies each record in a
table.
Data Type of a field refers to what kind of data can be stored in that field. Most frequently
used data types are: Text, Number, Currency, Date/Time.
When a website is developed to handle large amounts of data (like Online Reservation
System, Online Shopping, Online Banking), the relevant database is kept on the server and
server side scripts are used to manage this database. In almost all the cases, this database
is a Relational database. It means that the data is stored in the form of interrelated tables.
We can write scripts in PHP to manage relational databases. PHP supports many different
RDBMS: MySQL, MS Access, MS SQL Server, Oracle, DB2 etc. In this lesson we shall work
with MySQL, which is the most popular RDBM used with PHP. MySQL is a leading open
source, multiuser, and multithreaded RDBMS. Currently MySQL is owned by Oracle Corp.
(If you wish to connect PHP to MS Access, you can get the basic idea of how to do that from
the following link:
https://www.sitepoint.com/using-an-access-database-with-php/)
The PHP5 (and higher version) scripts can work with a MySQL database using the MySQLi (i
signifies improvement) extension or the PDO (PHP Data Objects). While PDO is capable of
working with 12 different database systems, MySQLi works only with MySQL databases.

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

Connecting with the database:


PHP provides mysqli_connect() function to open a database connection. This function takes
four parameters and returns a MySQL link identifier on success, or false on failure.
Syntax:
Mysqli_connect(server, user, password, databasename);

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.

user An optional parameter used to specify the username accessing the


database. If this is not specified then default is the name of the user that
owns the server process.

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.

databasenam An optional parameter used to specify the database to be used when


e performing queries.

Closing database connection:

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

connectio An optional parameter that specifies the connection reference to be used. If


n not specified then the last opened connection of mysqli_connect() will be
used.

sql Contains the SQL query to be executed.

Creating a database:
A database can be created using mysqli_query() function with suitable query. Example:
3
<?php

$servername = "localhost";

$username = "root";

$pwd = "faipskwt";

$conn = mysqli_connect($servername,$username, $pwd);

if (!$conn)

die("Could not connect".mysqli_error($conn));

$sql = "Create database Library";

if (mysqli_query($conn, $sql ))

echo "Database created successfully";

else

echo "database not created ".mysqli_error($conn);

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);
?>

Creating a table in the database:


To create a table in a database, we pass the query to create table as sql parameter in the
mysqli_query() function. Following is an example to create a table BOOKS with the structure:

Column AccNo Title Author Publisher Edition Price


Data INT(5) VARCHA VARCHAR(3 VARCHAR(1 INTEGER( DECIMAL(
Type R(30) 0) 0) 4) 7, 2)

<?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);
?>

Inserting records into a table:


To insert records into a table, we pass the relevant query as sql parameter in the
mysqli_query() function. The rules for inserting records are:
If column names are specified, then column count and value count should be the
same. If column names are not specified, then sequence and number of values should
be equal to the sequence and number of columns in the table.
If a column has a default value (auto-increment, NULL etc.), that column can be
omitted.
Except numeric values and NULL, other values need to be enclosed within single
quotes ( or ).

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));

$sql = "INSERT INTO Books VALUES (1001, 'Basic Economics', ";


$sql .= "'J.P.Mudgil', 'APH', 2009, 125)";
if (mysqli_query($conn, $sql))
echo "Record Inserted";
else echo "Error: ".$sql."<br>".mysqli_error($conn);
mysqli_close($conn);
?>

Retrieving data from a database:


Data can be retrieved from a database using the SELECT command of SQL. Following is an
example:

<?php

//PHP8-Example7

$servername = "localhost";

$username = "root";

$pwd = "faipskwt";

$db = "Library";

6
$conn = mysqli_connect($servername,$username, $pwd, $db);

if (!$conn)

die("Could not connect".mysqli_error($conn));

$sql = "Select Accno, Title, Author from Books";

$res = mysqli_query($conn, $sql);

$rows = mysqli_num_rows($res);

if ($rows > 0)

echo $rows. " rows selected<p>";

while ($row = mysqli_fetch_assoc($res))

{ echo "Accession Number: ".$row['Accno'];

echo ", Title: ".$row['Title'];

echo ", Author: ".$row['Author']."<BR>";

else echo "No rows found";

mysqli_close($conn);

?>

Updating data in a database:


Data can be updated in a database using the UPDATE command of SQL. Following is an
example to increase the price of each book by 20 if the books price is less than 150:

<?php

//PHP8-Example8

$servername = "localhost";

$username = "root";

7
$pwd = "faipskwt";

$db = "Library";

$conn = mysqli_connect($servername,$username, $pwd, $db);

if (!$conn)

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

$sql = "Update Books set Price = Price + 20 where Price < 150";

if (mysqli_query($conn, $sql))

$rows = mysqli_affected_rows($conn);

if ($rows > 0)

echo $rows." record(s) updated";

else echo "No record updated";

else echo "Error updating record(s) ".mysqli_error($conn);

mysqli_close($conn);

?>

Deleting data from a database:

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)

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

$sql = "Delete from Books where edition < 2006";

if (mysqli_query($conn, $sql))

$rows = mysqli_affected_rows($conn);

if ($rows > 0)

echo $rows." record(s) deleted";

else echo "No record deleted";

else echo "Error deleting record(s) ".mysqli_error($conn);

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'];

$conn = mysqli_connect($servername,$username, $pwd, $db);

if (!$conn)

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

$sql = "delete from BOOKS where Accno = $aNum";

if (mysqli_query($conn, $sql))

if (mysqli_affected_rows($conn)>0)

echo "Record deleted";

else echo "Record not found";

else echo "Error deleting record ".mysqli_error($conn);

mysqli_close($conn);

else

?>

<form method = post action = "<?php $_PHP_SELF ?>">

<table width = 400 cellspacing=1 cellpadding=2>

<tr>

<td width=100>Acession Number: </td>

<td><input name = AccNum type = text></td>

</tr>

10
<tr>

<td width = 100></td>

<td></td>

<tr>

<td width =100></td>

<td><input type=submit name="delete" value="Delete"></td>

</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

Write the PHP code to perform the following operations:


a. Add a new record into the Teacher table using a form, which takes input from
the user for all the details in the Teacher table.
b. Delete the records of all the teachers born before the year 1930.
c. Update the records for all teachers increasing their basic salary by Rs. 500.
11. Create a table called Users which contains the username and passwords of all the
users who are registered to access a particular website. Write the PHP code to
generate the login page, which authenticates the username and password from the
database table before granting access to the user to view the website and generates
an error message if the user does not enter correct username and password.
12. Create a table called GuestBook to store the feedback provided by users visiting your
schools website. It should have the following format:
Field Name Data Type Description
User_No Auto Number Primary Key
Name Text Visitors Name
Age Number Age of the visitor
Gender Text Visitors gender
Email Text Email address of the visitor
Comments Text Visitors comments about the web page.
Create the following form to take comments from the users and write a PHP script to
store the data entered by the user into the GuestBook table:

12
13

You might also like