Download as pdf or txt
Download as pdf or txt
You are on page 1of 32

PHP and databases

C S 2 2 0 S P R I N G 2020

TBS 2019-2020
Reminder (1/2)
2

 The script code is


executed by the server.

 The result is then sent to


the client in HTML.

 An interaction with a
database is possible on
the server side.
Reminder (2/2)
3

 PHP is processed by a PHP interpreter (or module) on the


web server.
Web server

Database Web client


5) HTML
2) PHP

Interpreter
Introduction to PHP and databases (1/3)
4

 PHP can operate with almost all the database management


systems (DBMS): Microsoft SQL server, Oracle, PostgreSQL, MySQL, Sybase,
SQLite, FilePro, Informix, Interbase, mSQL, dBase, Empress, etc.

 During this course we will be using MySQL (since we have


been using XAMPP in the past)

 MySQL is:
 A DBMS that has many advantages such as: rapidity, easy use, robustness, free, etc.

 Generally suitable and adapted to the majority of the small and medium sized
applications.

 PHP and MySQL are generally combined in the same offer by hosting platforms.
Introduction to PHP and databases (2/3)
5

 Prerequisites:
 The SQL language (Structured Query Language) to query databases
through SQL requests
 Database administration with PhpMyAdmin (available with XAMPP):
create, modify, add and delete databases and tables, etc.
Launch PhpMyAdmin :
 Go to : http://localhost/phpmyadmin

Or,
 via Xampp :
Start MySQL
and click on Admin
Introduction to PHP and databases (3/3)
6

 In order to use a database with PHP the following steps are


taken:

Connect Issue the query Disconnect

Select the database Exploit the results


API
7

 API: Application Programming Interface.

 Defines classes, methods, functions and variables that an application


will need to call in order to carry out its desired task.

 There are three popular available APIs to connect a PHP application


to a database:

 MySQL
 Mysqli
 PDO (PHP Data Objects)
MySQL vs Mysqli
8

MySQL: original extension to develop PHP applications that interact with a


MySQL database, used only with MySQL versions older than 4.1.3.

 Mysqli: MySQL improved extension, takes advantage of new features


found in MySQL systems versions 4.1.3 and newer, included with PHP
versions 5 and later.
 Benefits:
 Object-oriented interface
 Support for Prepared Statements
 Support for Multiple Statements
 Support for Transactions

 Enhanced debugging capabilities


 Embedded server support
PDO vs Mysqli (1/2)
9
 PDO (PHP Data Objects): provides a consistent API for PHP application
regardless of the type of database server.

 PDO vs Mysqli:
 PDO works on 12 different database systems (JDBC,DBI,..), whereas
Mysqli only works with MySQL databases.
 But, PDO doesn't allow to use all of the advanced features available
in Mysqli (e.g. support for Multiple Statements).
 Both are object-oriented, but MySQLi also offers a procedural API.
 Procedural API: functions are called to carry out tasks.
 Object-oriented API: classes are instantiated and then methods
are called on the resulting objects.
PDO vs Mysqli (2/2)
10

 Conclusion:

 You can choose Whatever you like!

 During this course we will use as an example MySQLi Procedural


The PHP-MySQLi functions (1/4)
11

• Connecting to the MySQL server:


$conn = mysqli_connect ($host,$user,$pass)
 $host: the name (or IP address) of the server hosting the database, in our case it
will be localhost (since we work on a local platform)

 $user: the username authorized to access the database server, in our case it is
“root”

 $pass: the associated password, in our case it is “” (empty) (to change your XAMPP
root MySQL password: http://veerasundar.com/blog/2009/01/how-to-change-the-
root-password-for-mysql-in-xampp/ )

 mysqli_connect(): returns false if the connection is not established and


the identifier $idcom if it is successful.

 Closing a connection: mysqli_close($conn)


The PHP-MySQLi functions (2/4)
12

 Selecting a database:

$conn = mysqli_connect($host,$user,$pass,$dbname)

 $dbname: the name of the database on which you want to operate (the
server may contain several databases.)

 mysqli_connect: returns true if the database exists and false


otherwise.

 Once the database is chosen, all the SQL requests are sent to this
database without having to specify it.
Example: connecting and choosing a database
13

 This PHP function allows to connect to a database:

1) Function definition
<?php
function connectDB($db)
{
$conn = mysqli_connect("localhost","root","", $db);
if (!$conn)
{ die("Connection failed: " .mysqli_connect_error());
}
Return true;
}

2) Function call
$v = connectDB("test");
if($v == true)
{
echo "Connection to the db test is successful";
}
else echo "Could not connect to the server of the database";
?>
The PHP-MySQLi functions (3/4)
14

 Interrogating a database:
mysqli_query($conn,$req)

 $req: a character string containing the text of the request sent to the
database server. This string must not finish with inverted commas “;”.

 If $req is a an add, delete or modify request, the function returns


true if the request is successful and false otherwise.

 If $req is a selection request, the function returns the result (a


table) if the request is successful and false otherwise.
Example: Interrogating a db with an SQL request
15

 Here is an example of a SELECT query coded in PHP:

<?php

$conn=mysqli_connect("localhost","root","","Library");

if ($conn==true)
{
$req = "SELECT * FROM Books WHERE author ='Balzac' ";
$res = mysqli_query($conn,$req);

if ($res==false)
echo "Cannot read the table";
else

}
?>
The PHP-MySQL functions (4/4)
16

Exploiting the results of a MySQL request:


 If it is an insertion request (INSERT INTO) or a deletion request (DELETE) or a
modification request (UPDATE), you just need to check if the request was
successfully executed.

 In the case of a selection request (SELECT), the result must be exploited:

mysqli_fetch_assoc ($res)
 $res is the result returned by the function mysqli_query().
 mysqli_fetch_assoc() returns a table containing one row of the result.

 Each call to this function returns the next row until it returns false (meaning there
are no rows left.)

 The named keys of the array are the names of the attributes in the original request.
 The content of each array box is the value of the attribute on the database.
Example
17

 Create a database named Results containing a table


Student (id, l_name, f_name, grade)
id is the the Primary Key of the table
including the following data :
id l_name f_name grade
01234567 Klibi Anas 12.53
01234568 Nabli Sourour 08.37
01234569 Tounsi Zied 10.65
01234560 Béji Imene 11.81
01234563 Karoui Aymen 07.72

 We want to display on a web page all the fields of the students


who have grades above 10.
Solution: Step 1
18

1) Create the database Results


o Go to: http://localhost/phpmyadmin
Or,
o via Xampp : Start MySQL
and click on Admin

o Create a database named “Results”

database
created
Solution: Step 2
19

2) Create a table named “Student” in the database Results


Solution: Step 3
20

3) Create its columns: id (int), l_name (text), f_name (text), grade (float).
Solution: Step 3
21

The table Student is created


Solution: Step 4
22

4) Insert data into the table Student : many ways


o Insert option -> Row by Row

SQL code
automatically
generated
Solution: Step 4
23

o SQL option -> write several SQL insert query (one for each row)
Solution: Step 4
24

o SQL option -> write one SQL insert query (for all the rows)
Solution: Step 4
25

o Import option -> importing data to your table from CSV file.
 A Comma-Separated Values (CSV) file stores tabular data in clear
text.
 Use Notepad++ or Excel to copy your data (slide 17) and save the
file as CSV file (data.csv).

Notepad++

Excel
Solution: Step 4
26

o In PhpMyAdmin, select import option and import the CSV file


containing the data.
Solution: Step 4
27

o All the rows are imported from the CSV file.


Solution: Step 5
28

5) Display display on PhpMyAdmin all the fields of the students who have
grades above 10.
o SQL option -> write a SELECT query
Solution: Step 5
29

--> Output on PhpMyAdmin


Solution: Step 5
30

--> Output on a web page : write a Php code -> to write on Notepad ++
<?php

$conn=mysqli_connect("localhost","root","", "Results");

if (!$conn)

{
die("Connection failed: " . mysqli_connect_error());
}
$req = "SELECT * FROM student WHERE grade >= 10.00";
$res = mysqli_query($conn,$req);

if (mysqli_num_rows($res) > 0)
{
While($line = mysqli_fetch_assoc($res))
{
echo $line[‘id’]." ". $line[‘l_name’]." ". $line[‘f_name’]." ". $line[‘grade’];
echo "<br>";
}
}
else {echo "0 results";}
mysqli_close($conn);
?>
Export a database
31
 Export option
 PhpMyAdmin generates an SQL file
(.sql) containing SQL queries (DDL,
DML).

 Note that such a file may also be written using


Notepad++ and must be saved as (.sql) file.
Import a database
32
 Import option
 Import an SQL file (.sql).

You might also like