0% found this document useful (0 votes)
29 views

Chapter 9(Php & Mysql Db)

Uploaded by

binmajedshort
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
29 views

Chapter 9(Php & Mysql Db)

Uploaded by

binmajedshort
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 27

Database Programming in PHP

Chapter 9
Objectives

2
Introduction

◼ The development of PHP has focused heavily


on database access, and as a result, it
provides driver support for more than 15
distinct databases systems.
◼ You may connect to and work with different
databases using PHP. Among
them, MySQL is the most widely used
database platform for PHP.
PHP Connect to MySQL

◼ PHP 5 and later can work with a MySQL


database using:
❑ MySQLi extension (the "i" stands for improved)
❑ PDO (PHP Data Objects)
◼ Earlier versions of PHP used the MySQL
extension. However, this extension was
deprecated in 2012.
Should I Use MySQLi or PDO?

◼ If you need a short answer, it would be "Whatever you


like".
◼ Both MySQLi and PDO have their advantages:
❑ PDO will work on more than 12 different database systems,
whereas MySQLi will only work with MySQL databases.
❑ So, if you have to switch your project to use another database,
PDO makes the process easy. You only have to change the
connection string and a few queries. With MySQLi, you will need
to rewrite the entire code - queries included.
❑ Both support Prepared Statements. Prepared Statements
protect from SQL injection, and are very important for web
application security.
MySQLi and PDO

◼ Here are two ways of working with PHP and


MySQL:
1) MySQLi
2) PDO
MySQLi Class

◼ The MySQLi class is the main class used to:


1) Set up a connection to the MySQL database
2) Send SQL queries to the MySQL database
(CRUD Operations)
3) Read results (if any) from the query
4) Check for any error connecting to or executing
SQL queries on a MySQL database
Establishing a Connection to the DB

◼ Four parameters are required to connect to


the database.
❑ Hostname (By default "localhost")
❑ Username (By default "root")
❑ Password (By default "No Password")
❑ Database Name
Example (MySQLi)
<?php

$servername = "localhost";
$username = “root";
$password = "";
$dbname = "database_name";

// Create connection
$conn = new MySQLi($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>

9
Tips

◼ The above example creates a successful


connection with Database if you provide valid
information.
◼ When the connection is not well, we can kill
that connection by using die() method.

10
Close the Connection

◼ The connection will be closed automatically


when the script ends.
◼ To close the connection before, use the
following:
❑ MySQLi:
◼ $conn->close();
Querying the DB via MySQLi
//Construct some query (it’s just a string)

2 Types of Queries
No Result Queries Result Queries
INSERT, DELETE, CREATE, etc… SELECT

PHP MySQL PHP MySQL


Insert Data into MySQL Using MySQLi

◼ After a database and a table have been created, we can start


adding data in them.
◼ Here are some syntax rules to follow:
❑ The SQL query must be quoted in PHP.
❑ String values inside the SQL query must be quoted.
❑ Numeric values must not be quoted.
❑ The word NULL must not be quoted.
◼ The INSERT INTO statement is used to add new records to a
MySQL table:
✓ INSERT INTO table_name (column1, column2, column3,...)
VALUES (value1, value2, value3,...)

13
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "testdb";

// Create connection
$conn = new MySQLi($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error){
die("Connection failed: " . $conn->connect_error);
}
else {
echo "Connected successfully";
$sql = "INSERT INTO tblstudent (SID, SName, SMark) VALUES (2, 'Ahmed', 99)";
}
if ($conn->query($sql)==TRUE) {
echo "New record created successfully";
}
else {
echo "Error: " . $conn->error;
}

$conn->close(); 14
?>
Delete Data From a MySQL Table Using MySQLi

◼ The DELETE statement is used to delete records from a table:

✓ DELETE FROM table_name WHERE some_column = some_value

◼ Notice
❑ The WHERE clause specifies which record or records that should be
deleted. If you omit the WHERE clause, all records will be deleted!

15
Create the Connection File with Name (DBConnect.php)

<?php DBConnect.php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "testdb";

// Create connection
$conn = new MySQLi($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error){
die("Connection failed: " . $conn->connect_error);
}
else {
echo "Connected successfully";
}
?>
16
Create the Deletion File with Name (Deletefile.php)

<?php Deletefile.php
// Include the connection file
require_once "DBConnect.php";

// Create the Deletion Commend


$sql = "DELETE FROM tblstudent WHERE sid=1";

if ($conn->query($sql)==TRUE) {
echo "Record deleted successfully";
}
else {
echo "Error: " . $conn->error;
}

$conn->close();
?>

17
Update Data in a MySQL Table Using MySQLi

◼ 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

◼ Notice
❑ The WHERE clause specifies which record or records that should be
updated. If you omit the WHERE clause, all records will be updated!

18
Create the Updating File with Name (Updatefile.php)
Updatefile.php
<?php
// Include the connection file
require_once "DBConnect.php";

// Create the Update Commend


$sql = "UPDATE tblstudent SET SNAME="Mohammed" WHERE SID=1";

if ($conn->query($sql)==TRUE) {
echo "Record Updated successfully";
}
else {
echo "Error: " . $conn->error;
}

$conn->close();
?>

19
Select Data With MySQLi
◼ The SELECT statement is used to select data from one or
more tables:
❑ SELECT column_name(s) FROM table_name
◼ or we can use the * character to select ALL columns from a
table:
❑ SELECT * FROM table_name

◼ The following example columns from the student table and


displays the result on the page

20
Create the Select File with Name (Selectfile.php)
Selectfile.php
<?php
// Include the connection file
require_once "DBConnect.php";
// Create the Select Commend
$sql = "SELECT * FROM tblstudent";
$result= $conn->query($sql);
if ($result->num_rows >0) {
while($row=$result->FETCH_ASSOC()){
echo "SID:" . $row["SID"] . "<br>";
echo "SNAME: " . $row["SName"] . "<br>";
echo "SMark:" . $row["SMark"] . "<br>";
}}
else {
echo "0 result";
}
$conn->close();
?>

21
Prepared Statements in MySQLi

◼ Compared to executing SQL statements directly, prepared


statements have three main advantages:
❑ Prepared statements reduce parsing time.
❑ Bound parameters minimize bandwidth to the server as you need
send only the parameters each time, and not the whole query.
❑ Prepared statements are very useful against SQL injections.

22
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error); }
// Prepare and bind
$stmt = $conn->prepare("INSERT INTO MyGuests (firstname, lastname,
email) VALUES (?, ?, ?)");
$stmt->bind_param("sss", $firstname, $lastname, $email);
// Set parameters and execute
$firstname = "John";
$lastname = "Doe";
$email = "[email protected]";
if ($stmt->execute()) {
echo "New records created successfully";
} else {
echo "Error: " . $stmt->error;}
// Close statement and connection
$stmt->close();
$conn->close();
?> 23
Prepared Statements in MySQLi …

◼ This function binds the parameters to the SQL query and tells
the database what the parameters are "sss" argument lists the
types of data that the parameters are.
◼ The s character tells mysql that the parameter is a string.
◼ The argument may be one of four types:
❑ i - integer
❑ d - double
❑ s - string
❑ b - BLOB
◼ We must have one of these for each parameter.

24
Limit Data Selections From a MySQL Database

◼ MySQL provides a LIMIT clause that is used to specify the


number of records to return.
◼ The LIMIT clause makes it easy to code multi page results or
pagination with SQL, and is very useful on large tables.
◼ Assume we wish to select all records from 1 - 30 (inclusive)
from a table called "Orders".
◼ The SQL query would then look like this:
❑ $sql = "SELECT * FROM Orders LIMIT 30";
◼ When the SQL query above is run, it will return the first 30
records.

25
What if we want to select records 16 - 25 (inclusive)?

◼ Mysql also provides a way to handle this: by using OFFSET.


◼ The SQL query below says "return only 10 records, start on
record 16 (OFFSET 15)":
❑ $sql = "SELECT * FROM Orders LIMIT 10 OFFSET 15";
◼ You could also use a shorter syntax to achieve the same
result:
❑ $sql = "SELECT * FROM Orders LIMIT 15, 10";
❑ Notice that the numbers are reversed when you use a comma.

26

You might also like