Chapter : Three
Manipulating Databases with PHP
3.1. Introduction
• One of the reasons for PHP’s popularity as a Web scripting language is its
(cross-platform, compatible, scalability, Allows for various DBs …. etc)
• Allows for various DB formats (Microsoft SQL Server, IBM DB2,
PostgreSQL, MySQL, and Oracle. )
• Makes it easy for Web developers to create Web applications quickly and
efficiently.
Database Access in PHP
• Database: is a separate application that stores a collection of data.
• Table: is a set of rows and columns. It represents a single concept such as
products.
• Column: a set of data of single data type. Ex. FirstName, LastName,
• Row: single record of data. Ex. “Abebe”, “Kebede”,
• Field: is the intersection of a row and a column. Ex. FirstName: ”Abebe”
• Redundancy: Storing data twice, redundantly to make the system faster.
Cont.…
• Primary Key: is unique a key value can not occur twice in one table.
• Foreign Key: A foreign key is the linking pin between two tables.
• Compound Key: (composite key) is a key that consists of multiple
columns, because one column is not sufficiently unique.
• Referential Integrity: Referential Integrity makes sure that a foreign key
value always points to an existing row.
MySQL Database:
• MySQL is becoming so popular because of many good reasons.
• MySQL works on many operating systems and with many languages including
PHP, PERL, C, C++, JAVA, etc.
• MySQL works very quickly and works well even with large data sets.
• MySQL is very friendly to PHP, the most appreciated language for web
development.
• MySQL supports large databases, up to 50 million rows or more in a table.
• The default file size limit for a table is 4GB, but you can increase this (if your
operating system can handle it) to a theoretical limit of 8 million terabytes (TB).
Database Interactions
PHP database interactions in five steps:
Create a database connection
Perform Database query
Use returned data if any
Release returned data
Close database connection
Creating a Database Connection:
• Before we enable do anything with database in PHP, we should first connect
to the MySQL server using specific connection variables.
• Connection variables consist of the following common parameters.
• Host name: This is the name of the server. We can change to whatever host
is acting as MySQL server. It is optional (localhost).
• User name: The root user of the system. It is require (root).
• User’s password:-This is encrypted written with the form for security. It is
require (” “);
Cont.…
• The common function in PHP that uses for server connection is
mysql_connect( ) or mysqli_connect() function.
• This function has the following syntax:- mysql_connect ("hostname",
"user", "pass") to connect with MySQL server.
• PHP provides mysql_connect function to open a database connection. This
function can take up to five parameters and returns a MySQL link identifier
on success, or FALSE on failure.
• The five parameters are the three above and the two below options.
Cont.…
• new_link Optional - If a second call is made to mysql_connect() with the same arguments,
no new connection will be established; instead, the identifier of the already opened
connection will be returned.
• client_flags Optional - A combination of the following constants:
MYSQL_CLIENT_SSL - Use SSL encryption
MYSQL_CLIENT_COMPRESS - Use compression protocol
MYSQL_CLIENT_IGNORE_SPACE - Allow space after function names
MYSQL_CLIENT_INTERACTIVE - Allow interactive timeout
seconds of inactivity before closing the connection
• Note: There are more available parameters, but the ones listed above are the
most important.
Databaseconnection.php
• <?php
• $dbhost = “localhost”; Optional – you can placed “”, but you couldn’t placed any
char.
• $dbuser = 'root'; Require, Warning: Access denied for user ''@'localhost' to database “aip”
• $dbpass = “"; Require, Access denied for user 'root'@'localhost' (using password: YES)
• $conn = mysqli_connect($dbhost, $dbuser, $dbpass,“Aip");
• if(! $conn )
• {
• die('Could not connect: ' . mysqli_error()); }
• echo 'Connected successfully';
• mysqli_close($conn);
• ?>
Closing a DB connection
• You can disconnect from MySQL database anytime using another PHP function
mysql_close().
• This function takes a single parameter which is a connection returned by
mysql_connect() function.
Syntax:
mysql_close ( resource $link_identifier );
mysqli_close($conn); or mysql_close($conn);
• This function returns true if it closes connection successfully otherwise it returns
false.
Cont.…
• There are also functions in PHP which have different purposes. For instance,
• mysql_select_db("database name") or
mysqli_select_db(“connection”,"database name") : Equivalent to the
MySQL command USE; makes the selected database the active one.
• mysqli_query("query"): Used to send any type of MySQL command to the
server.
• mysqli_fetch_rows("results variable from query"): Used to return a row of
the entire results of a database query.
Cont.…
• mysqli_affected_rows():Print out affected rows from different queries:
• mysql_fetch_array("results variable from query"): Used to return several
rows of the entire results of a database query.
• mysql_free_result(“result variable from query”): Used to release the
returned results.
• mysql_error(): Shows the error message that has been returned directly from
the MySQL server.
Creating the working Database
• After establishing a MySQL connection with the code above, you then need to
choose which database you will be using with this connection.
• This is done with the mysql_select_db(“database-name”)or
mysqli_select_db(“connection”,”databasename”) function.
• If the database you are looking to work on is not available, you can create it using
mysql_query() or mysqli_query() function together with CREATE command
followed by database name. mysql_query function can take two parameters and
returns TRUE on success or FALSE on failure.
• The parameters are:- sql and connection.
Cont..
• The syntax of the function is:-
• mysql_query(sql, connection variable); or
• mysqli_query(connection variable,sql);
• To create a database uses the following sql syntax:
• CREATE DATABASE database_name
• mysql_query ("create database test”,$connection): told MySQL to create a
database called test.
Cont..
• die(mysql_error()); will print out an error if there is a problem in the
database creation process.
• Closing Query
• When you are finished working with query results retrieved with the
mysql_query() function, use the mysql_free_result() function to close the
resultset
• To close the resultset, pass to the mysql_free_result() function the variable
containing the result pointer from the mysql_query() function
Recommended
• Use database connection and database creation at one file extension.
• Syntax: $sql or $sqli="CREATE DATABASE databasename";
• if ($conn->query($sqli) === TRUE) {
• echo "Database created successfully";
• } else {
• echo "Error creating database: " . mysqli_error();
•}
• mysqli_close($conn);
Cont..
•<?php
•$dbhost = 'localhost'; // can you change the order of parameters during declaration?
• $dbuser = 'root';
•$dbpass = '';
• $conn = mysqli_connect($dbhost, $dbuser, $dbpass);
• if(! $conn )
•{
• die('Could not connect: ' . mysqli_error());
•}
• echo 'Connected successfully';
•//mysqli_close($conn); don’t placed here!!!
Cont..
• // Create database
• $sqli = "CREATE DATABASE TESTTEST";
• if ($conn->query($sqli) === TRUE) {
• echo "Database created successfully";
• } else {
• echo "Error creating database: " . mysqli_error($conn);
•}
• mysqli_close($conn);
• ?>
Create Table MySQL
• Before you enter data (rows) into a table, you must first define what kinds of
data will be stored (columns).This can be done using Create sql statement.
• A database table has its own unique name and consists of columns and rows.
• Syntax:
• CREATE TABLE table_name (column_name1 data_type,column_name2
data_type,....)
• We are now going to design a MySQL query to summon our table from
database test.
Cont..
• <?php
• $dbhost = 'localhost';
• $dbuser = 'root';
• $dbpass = '';
• $conn = mysqli_connect($dbhost, $dbuser, $dbpass,"Aip");
• if(! $conn )
• {
• die('Could not connect: ' . mysqli_error());
• }
• echo 'Connected successfully';
• //mysqli_close($conn);
• // sql to create table
Cont..
• $// sql to create table
• $sqli = "CREATE TABLE Thirdyear2014 (
• Name VARCHAR(50) ,
• Code INT (20) )";
• if (mysqli_query($conn, $sqli)) {
• echo "Table Thirdyear created successfully";
• } else {
• echo "Error creating table: " . mysqli_error($conn);
•}
• mysqli_close($conn);
• ?>
Send/Insert Data to a Database
• When data is put into a MySQL table it is referred to as inserting data. When
inserting data it is important to remember the exact names and types of the
table's columns.
• Syntax:
• INSERT INTO table_name VALUES (value1, value2, value3,...) Or
• INSERT INTO table_name (column1, column2,...) VALUES (value1, value2,...)
• Requirements : form, database connection, the file name which is saved by the
action value(5-ddbb) .
Dbform,php
• <!DOCTYPE html>
• <html>
• <head>
• <title></title>
• </head>
• <body>
• <form action="5-DDBB.php" method="POST">
• name:<input type="text" name="name"><br><br>
• code:<input type="text" name="code"><br><br>
• <input type="submit" name="register" value="Register">
• </form>
• </body>
• </html>
5-DDBB.php
• <?php
• $host="localhost";
• $user="root";
• $pas="";
• $conn=mysqli_connect($host,$user,$pas,"aip");
• if (!$conn)
• {
• die("Could not connect");
•}
• else {
• echo "Database Successfully Connected"."<br>";
•}
Cont..
• if (isset($_POST["register"])) {
• $Name=$_POST["name"];
• $Code=$_POST["code"];
• $sqli="INSERT INTO
exam(Name,Code)values('$Name','$Code')";
• if (mysqli_query($conn,$sqli)) {
• echo "new record inserted successfuly";
• }
• else
• echo "Error".mysqli_error($conn);
•}
• mysqli_close($conn)
• ?>
Retrieve Data from a Database
• In MySQL, data is retrieved with the "SELECT" keyword.
• The SELECT statement is used to select data from a database or we can
use the * character to select ALL columns from a table:
• SELECT * FROM table_name
• Before attempting to retrieve data, be sure that you have created a table
that contains some data.
• Syntax: SELECT column_name(s) FROM table_name
Cont..
• <?php
• $dbhost = 'localhost';
• $dbuser = 'root';
• $dbpass = '';
• $conn = mysqli_connect($dbhost, $dbuser, $dbpass,"aip");
• if(! $conn )
• {
• die('Could not connect: ' . mysqli_error());
• }
• $sqli = "SELECT name, code FROM exam";
• $result = $conn->query($sqli);
Cont..
• if ($result->num_rows > 0) {
• echo "<table border=1> <tr> <th> NAME </th> <th> CODE</th>
</tr>";
• while ( $row=$result->fetch_assoc()) {
• echo "<tr> <td>".$row["name"]."</td>"."<td>".
$row["code"]."</td> </tr>" ;
• }
• echo "</table>";
• } else {
• echo "0 results";
•}
• $conn->close();
• ?>
Select and Filter Data From a MySQL Database
• The WHERE clause is used to filter records.
• The WHERE clause is used to extract only those records that fulfill a specified
condition.
• SELECT column_name(s) FROM table_name WHERE column_name operator
value
• $sqli = "SELECT Name, code FROM exam WHERE Code=30";
Modify/Updating Existing Data
• The UPDATE statement is used to update existing records in a table.
• UPDATE table_name SET column1=value, column2=value2,... WHERE
some_column=some_value
• Let's look at the “exam" table before UPDATE:
$sqli = "UPDATE exam SET Code=60 WHERE Code=30";
Update
<?php
$host="localhost";
$user="root";
$pas="";
$conn=mysqli_connect($host,$user,$pas,"aip");
if(!$conn)
{
die("could not connected".mysqli_error($conn));
}
$sqli = "UPDATE exam SET Code=60 WHERE Code=30";
if ($conn->query($sqli) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $conn->error;
}
$conn->close();
?>
Remove Existing Data
• The DELETE query is very similar to the UPDATE Query.
• We need to choose a table, tell MySQL to perform the deletion, and provide the
requirements that a record must have for it to be deleted.
• Syntax:DELETE from table_name where column_name comparison_operator
value
• Let's look at the “exam" table before DELET:
$sqli = "delete from exam WHERE code=3030";
Delete
• <?php
• $host="localhost";
• $user="root";
• $pas="";
• $conn=mysqli_connect($host,$user,$pas,"aip");
• if(!$conn)
• {
• die("could not connected".mysqli_error($conn));
• }
• $sqli = "delete from exam WHERE code=3030";
• if ($conn->query($sqli) === TRUE) {
• echo "Record Delete successfully";
• } else {
• echo "Error Delete record: " . $conn->error;
• }
• $conn->close();
Data base security using server side scripting
• Nowadays, databases are fundamental components of any web based
application by enabling websites to provide varying dynamic content.
• Since very sensitive or secret information can be stored in a database, you
should strongly consider protecting your databases.
• To retrieve or to store any information you need to connect to the
database, send a legitimate query, fetch the result, and close the
connection.
Encryption in PHP
• Once an attacker gains access to your database directly (bypassing the web
server), stored sensitive data may be exposed or misused, unless the
information is protected by the database itself.
• Encrypting the data is a good way to mitigate this threat, but very few
databases offer this type of data encryption.
• The easiest way to work around this problem is to first create your own
encryption package, and then use it from within your PHP scripts.
• PHP provides different types of encryptions such as: md5, sha1, hash, crypt,
hashed_password etc.
Cont..
Example:
<?php
$pass="12345678";
echo "md5 encryption $pass=".md5($pass)."<br>";
echo "sha1 encryption $pass=".sha1($pass)."<br>";
echo "hash encryption $pass=".hash('sha1',$pass)."<br>";
echo "crypt encryption $pass=".crypt($pass,$salt);
?>
Output:
md5 encryption 12345678=25d55ad283aa400af464c76d713c07ad
sha1 encryption 12345678=7c222fb2927d828af22f592134e8932480637c0d
hash encryption 12345678=7c222fb2927d828af22f592134e8932480637c0d
crypt encryption 12345678=$1$.90.tj5.$CG0sUopGFc1ADWxBqDjPu.
In the above example, the salt parameter is optional. However, crypt () creates a weak password
without the salt. Make sure to specify a strong enough salt for better security.
Thank You!!!