0% found this document useful (0 votes)
43 views35 pages

Chapter Seven

The document discusses connecting PHP to MySQL databases using MySQLi and PDO. It explains how to establish a connection, create tables, insert data, and run select queries. Code examples are provided for each task using both MySQLi and PDO approaches.

Uploaded by

eliasferhan1992
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
43 views35 pages

Chapter Seven

The document discusses connecting PHP to MySQL databases using MySQLi and PDO. It explains how to establish a connection, create tables, insert data, and run select queries. Code examples are provided for each task using both MySQLi and PDO approaches.

Uploaded by

eliasferhan1992
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 35

Chapter Seven

PHP Database connectivity


• The collection of related data is called a database.
How we can connect PHP to MySQL?
• PHP 5 and later can work with a MySQL database using:
• MySQLi extension (the ‘i’ is abbreviation for improved)
• PDO (PHP Data Objects)
Which one should we use MySQLi or PDO?
• Both MySQLi and PDO have their recompenses:
• PDO will work with 12 different database systems, whereas MySQLi will
only work with MySQL databases.
• So, if you have to shift your project to use alternative 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 complete
code — queries included.
• Both are object-oriented, but MySQLi also offers a procedural API.
Connection to MySQL using MySQLi
• PHP provides mysql_connect() function to open a database
connection.
• This function takes a single parameter, which is a connection returned
by the mysql_connect() function.
• You can disconnect from the MySQL database anytime using another
PHP function mysql_close().
• There is also a procedural approach of MySQLi to establish a
connection to MySQL database from a PHP script.
MySQLi Object-Oriented
<?php
$servername = "localhost";
$username = "username";
$password = "password";
// Connection
$conn = new mysqli($servername, $username, $password);
// For checking if connection is successful or not
if ($conn->connect_error) {
die("Connection failed: ". $conn->connect_error);
}
echo "Connected successfully";
?>
MySQLi Procedural
<?php
$servername = "localhost";
$username = "username";
$password = "password";
// Connection
$conn = mysqli_connect($servername, $username, $password);
// Check if connection is Successful or not
if (!$conn) {
die("Connection failed: ". mysqli_connect_error());
}
echo "Connected successfully";
?>
Connection to MySQL using PDO
<?php
$servername = "localhost";
$username = "username";
$password = "password";
try {
$conn = new PDO("mysql:host=$servername;dbname=myDB", $username,
$password);
// Set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
} catch(PDOException $e) {
echo "Connection failed: ". $e->getMessage();
}
?>
PHP | MySQL ( Creating Table )
• What is a table? In relational databases, a table is a set of data elements
using a model of vertical columns and horizontal rows, the cell being the
unit where a row and column intersect.
• A table has a specified number of columns, but can have any number of
rows.
• Creating a MySQL Table Using MySQLi and PDO
• The steps to create table are similar to creating databases.
• The difference is instead of creating a new database we will connect to
existing database and create a table in that database.
• To connect to an existing database we can pass an extra variable “database
name” while connecting to MySQL. The CREATE TABLE statement is
used to create a table in MySQL.
• In this article, a table named “employees”, with four columns: “id”,
“firstname”, “lastname” and “email” will be created.
1.The data types that will be used are :VARCHAR:Holds a variable
length string that can contain letters, numbers, and special characters.
The maximum size is specified in parenthesis.
2.INT :the INTEGER data type accepts numeric values with an implied
scale of zero. It stores any integer value between -2147483648 to
2147483647.
3.The attributes that are used along with data types in this article
are:NOT NULL: Each row must contain a value for that column, null
values are not allowed.
4.PRIMARY KEY: Used to uniquely identify the rows in a table. The
column with PRIMARY KEY setting is often an ID number.
Creating table using MySQLi Object- // sql code to create table
oriented Procedure Syntax : $sql = "CREATE TABLE employees(
<?php id INT(2) PRIMARY KEY,
$servername = "localhost"; firstname VARCHAR(30) NOT NULL,
$username = "username"; lastname VARCHAR(30) NOT NULL,
$password = "password"; email VARCHAR(50)
$dbname = "newDB"; )";
// checking connection if ($conn->query($sql) === TRUE) {
$conn = new mysqli($servername, echo "Table employees created
$username, $password, $dbname); successfully";
} else {
// Check connection
echo "Error creating table: " . $conn>error;
if ($conn->connect_error) {
}
die("Connection failed: " .
$conn>connect_error); $conn->close();
?>
}
Creating table using MySQLi Procedural procedure Syntax :
<?php // sql code to create table
$servername = "localhost"; $sql = "CREATE TABLE employees (
id INT(2) PRIMARY KEY,
$username = "username";
firstname VARCHAR(30) NOT NULL,
$password = "password"; lastname VARCHAR(30) NOT NULL,
$dbname = "newDB"; email VARCHAR(50)
// Checking connection )";
$conn = mysqli_connect($servername, if (mysqli_query($conn, $sql)) {
$username, $password, $dbname); echo "Table employees created successfully";
} else {
// Check connection
echo "Error creating table: " .
if (!$conn) { mysqli_error($conn);
die("Connection failed: " . }
mysqli_connect_error()); mysqli_close($conn);
} ?>
Creating table using PDO procedure Syntax :
// sql code to create table
<?php $sql = "CREATE TABLE employees ( id INT(6)
$servername = "localhost"; UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,
$username = "username";
lastname VARCHAR(30) NOT NULL,
$password = "password"; email VARCHAR(50) )";
$dbname = "newDB"; // using exec() because no results are returned
try { $conn->exec($sql);
echo "Table employees created successfully";
$conn = new
PDO("mysql:host=$servername;dbname=$ }
dbname", $username, $password); catch(PDOException $e)
{
// setting the PDO error mode to
exception echo $sql . "" . $e->getMessage();
}
$conn>setAttribute(PDO::ATTR_ERRMO
$conn = null;
DE, PDO::ERRMODE_EXCEPTION);
?>
PHP | Inserting into MySQL database
• INSERT INTO statement is used to insert new rows in a database
table.
• Let’s see the syntax how to insert into table, considering database
already exists. SYNTAX :
INSERT INTO TABLE_NAME (column1, column2, column3, ... columnN)
VALUES (value1, value2, value3, ...valueN);
• Here, column1, column2, column3, …columnN are the names of the
columns in the table into which you want to insert the data.
Creating table using MySQLi Object-oriented Procedure :
<?php
$mysqli = new mysqli("localhost", "root", "", "newdb");
if ($mysqli == = false) {
die("ERROR: Could not connect. ".$mysqli->connect_error); }
$sql = "INSERT INTO mytable (firstname, lastname, age) VALUES('ram', 'singh', '25') ";
if ($mysqli->query($sql) == = true) {
echo "Records inserted successfully."; }
else{
echo “ERROR: Could not able to execute $sql. “.$mysqli->error;
}
// Close connection
$mysqli->close();
?>
Creating table using MySQLi PDO Procedure :
<?php
try {
$pdo = new PDO("mysql:host=localhost;dbname=newdb", “root", "");
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch (PDOException $e) {
die("ERROR: Could not connect. ".$e->getMessage()); }
try {
$sql = "INSERT INTO mytable (first_name, last_name, age) VALUES('ram', 'singh', '25') ";

$pdo->exec($sql);
echo "Records inserted successfully.";
}
catch (PDOException $e) {
die("ERROR: Could not able to execute $sql. “ .$e->getMessage()); }
// Close connection
unset($pdo);
?>
PHP | MySQL Select Query
• The SQL SELECT statement is used to select the records from
database tables.
Syntax : The basic syntax of the select clause is
SELECT column1_name,column2_name,columnn_name FROM
table_name;
To select all columns from the table, the * character is used.
SELECT * FROM table_name;
To select all the data stored in the ‘ Data ‘ table, we will use the code
mentioned below. SELECT Query using Procedural Method :
<?php while ($row = mysqli_fetch_array($res))
$link = mysqli_connect("localhost", { echo "<tr>";
"root", "", "Mydb"); echo "<td>".$row['Firstname']."</td>";
echo "<td>".$row['Lastname']."</td>";
if ($link === false) { die("ERROR:
echo "<td>".$row['Age']."</td>";
Could not connect.
echo "</tr>";
".mysqli_connect_error());
}
} echo "</table>";
$sql = "SELECT * FROM Data"; mysqli_free_result($res);
if ($res = mysqli_query($link, $sql)) }
{ else {
if (mysqli_num_rows($res) > 0) { echo "No matching records are found.";
echo "<table>"; }}
echo "<tr>"; else {
echo "<th>Firstname</th>"; echo "ERROR: Could not able to execute
$sql. “ .mysqli_error($link);
echo "<th>Lastname</th>";
}
echo "<th>age</th>"; mysqli_close($link);
echo "</tr>"; ?>
Code Explanation:
1.The “res” variable stores the data that is returned by the
function mysql_query().
2.Everytime mysqli_fetch_array() is invoked, it returns the next row
from the res() set.
3.The while loop is used to loop through all the rows of the table “data”.
SELECT Query using Object Oriented Method :
<?php while ($row = $res->fetch_array())
$mysqli = new mysqli("localhost", "root", {
"", "Mydb"); echo "<tr>";
if ($mysqli === false) { echo "<td>".$row['Firstname']."</td>";
echo "<td>".$row['Lastname']."</td>";
die("ERROR: " .$mysqli->connect_error);
echo "<td>".$row['Age']."</td>";
} echo "</tr>";
$sql = "SELECT * FROM Data"; }
if ($res = $mysqli->query($sql)) { echo "</table>";
if ($res->num_rows > 0) { $res->free();
echo "<table>"; }
else {
echo "<tr>";
echo "No matching records are found.";
echo }}
"<th>Firstname</th>"; else {
echo echo "ERROR: Could not execute $sql. " .
"<th>Lastname</th>"; $mysqli->error;
echo "<th>Age</th>"; }
echo "</tr>"; $mysqli->close();
?>
SELECT Query using PDO Method :
<?php while ($row = $res->fetch()) {
echo "<tr>";
try { $pdo = new PDO("mysql:host = localhost; dbname=mydb", "root", "");
echo
$pdo->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION); "<td>".$row['Firstname']."</td>";
echo
} "<td>".$row['Lastname']."</td>";
catch (PDOException $e) { echo "<td>".$row['Age']."</td>";
echo "</tr>";
die("ERROR: Could not connect. ".$e->getMessage()); } }
try { $sql = "SELECT * FROM Data"; echo "</table>";
unset($res);
$res = $pdo->query($sql);
}
if ($res->rowCount() > 0) { else {
echo "No matching records are
echo "<table>";
found.";
echo "<tr>"; }}
catch (PDOException $e) {
echo "<th>Firstname</th>";
die("ERROR: Could not able to execute
echo "<th>Lastname</th>"; $sql. " .$e->getMessage());
}
echo "<th>Age</th>";
unset($pdo);
echo "</tr>"; ?>
PHP | MySQL Delete Query
• The DELETE query is used to delete records from a database table.
• It is generally used along with the “Select” statement to delete only
those records that satisfy a specific condition.
• Syntax : The basic syntax of the Delete Query is

• Let us consider the following table “Data” with four columns ‘ ID ‘, ‘


FirstName ‘, ‘ LastName ‘ and ‘ Age ‘.
• To delete the record of the person whose ID is 201 from the ‘ Data ‘
table, the following code can be used. Delete Query using
Procedural Method :
<?php
$link = mysqli_connect("localhost", "root", "", "Mydb");
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
$sql = "DELETE FROM Data WHERE ID=201";
if(mysqli_query($link, $sql)){
echo "Record was deleted successfully.";
}
else{
echo "ERROR: Could not able to execute $sql. ". mysqli_error($link);
}
mysqli_close($link);
?>
Delete Query using Object Oriented Method :
<?php
$mysqli = new mysqli("localhost", "root", "", "Mydb");
if($mysqli === false){
die("ERROR: Could not connect. " . $mysqli->connect_error);
}
$sql = "DELETE FROM Data WHERE ID=201";
if($mysqli->query($sql) === true){
echo "Record was deleted successfully.";
} else{
echo "ERROR: Could not able to execute $sql. ". $mysqli->error;
}
$mysqli->close();
?>
Delete Query using PDO Method :

<?php
try{
$pdo = new PDO("mysql:host=localhost; dbname=Mydb", "root", "");
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e){
die("ERROR: Could not connect. " . $e->getMessage());
}
try{
$sql = "DELETE FROM Data WHERE ID=201";
$pdo->exec($sql);
echo "Record was deleted successfully.";
} catch(PDOException $e){
die("ERROR: Could not able to execute $sql. ". $e->getMessage());
}
unset($pdo);
?>
PHP | MySQL WHERE Clause
• The WHERE Clause is used to filter only those records that are fulfilled by a specific
condition given by the user.
• in other words, the SQL WHERE clause is used to restrict the number of rows affected
by a SELECT, UPDATE or DELETE query.
• Syntax : The basic syntax of the where clause is –
SELECT Column1 , Column2 , …. FROM Table_Name WHERE Condition
Implementation of WHERE Clause :
• To select all the rows where the “Firstname” is “ram”, we will use the following code :
Where Clause using Procedural Method :
<?php while($row = mysqli_fetch_array($res)){
$link = mysqli_connect("localhost", "root", "", echo "<tr>";
"Mydb"); echo "<td>" . $row['Firstname'] . "</td>";
if($link === false){ echo "<td>" . $row['Lastname'] . "</td>";
die("ERROR:connect.".mysqli_connect_error()); echo "<td>" . $row['Age'] . "</td>";
} echo "</tr>";
}
$sql = "SELECT * FROM Data WHERE
Firstname='ram'"; echo "</table>";
mysqli_free_result($res);
if($res = mysqli_query($link, $sql)){
} else{
if(mysqli_num_rows($res) > 0){
echo "No Matching records are found.";
echo "<table>";
}
echo "<tr>"; } else{
echo "<th>Firstname</th>"; echo "ERROR: Could not able to execute $sql. ".
echo "<th>Lastname</th>"; mysqli_error($link);
echo "<th>age</th>"; }
mysqli_close($link);
echo "</tr>";
Code Explanation :
1.The “res” variable stores the data that is returned by the
function mysql_query().
2.Everytime mysqli_fetch_array() is invoked, it returns the next row
from the res() set.
3.The while loop is used to loop through all the rows of the table “data”.
Where Clause using Object Oriented Method :
while($row = $res->fetch_array()){
<?php
echo "<tr>";
$mysqli = new mysqli("localhost", "root", "", "Mydb");
echo "<td>" . $row['Firstname'] . "</td>";
if($mysqli === false){
echo "<td>" . $row['Lastname'] . "</td>";
die("ERROR: Could not connect. ". $mysqli->connect_error);
echo "<td>" . $row['Age'] . "</td>";
}
echo "</tr>";
$sql = "SELECT * FROM Data WHERE Firstname='ram'";
}
if($res = $mysqli->query($sql)){
echo "</table>";
if($res->num_rows > 0){
$res->free();
echo "<table>";
} else{
echo "<tr>";
echo "No matching records are found."; }
echo "<th>Firstname</th>";
} else{
echo "<th>Lastname</th>";
echo "ERROR: Could not execute $sql. ".
echo "<th>Age</th>";
$mysqli->error;
echo "</tr>";
}

$mysqli->close();
Where Clause using PDO Method :
<?php
while($row = $res->fetch()){
try{ echo "<tr>";
$pdo = new PDO("mysql:host=localhost; dbname=Mydb", echo "<td>" . $row['Firstname'] . "</td>";
"root", "");
echo "<td>" . $row['Lastname'] . "</td>";
$pdo- echo "<td>" . $row['Age'] . "</td>";
>setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION); echo "</tr>";
} catch(PDOException $e){ }
die("ERROR: not connect. ". $e->getMessage()); } echo "</table>";
try{ unset($res);
$sql = "SELECT * FROM Data WHERE Firstname='ram'"; } else{
$res = $pdo->query($sql); echo "No records matching are found."; }
if($res->rowCount() > 0){ } catch(PDOException $e){
echo "<table>"; die("ERROR: Could not able to execute
echo "<tr>"; $sql. " . $e->getMessage());
}
echo "<th>Firstname</th>";
unset($pdo);
echo "<th>Lastname</th>"; ?>
echo "<th>Age</th>";
echo "</tr>";
PHP MySQL UPDATE Query
• The MySQL UPDATE query is used to update existing records in a
table in a MySQL database.
• It can be used to update one or more field at the same time.
• It can be used to specify any condition using the WHERE clause.
• Syntax : The basic syntax of the Update Query is –
Implementation of Where Update Query :
• Let us consider the following table “Data” with four columns ‘ID’,
‘FirstName’, ‘LastName’ and ‘Age’.

• To update the “Age” of a person whose “ID” is 201 in the “Data”


table, we can use the following code :
Update Query using Procedural Method

<?php
$link = mysqli_connect("localhost", "root", "", "Mydb");

if($link === false){


die("ERROR: Could not connect. ". mysqli_connect_error());
}

$sql = "UPDATE data SET Age='28' WHERE id=201";


if(mysqli_query($link, $sql)){
echo "Record was updated successfully.";
} else {
echo "ERROR: Could not able to execute $sql. ". mysqli_error($link);
}
mysqli_close($link);
?>
Update Query using Object Oriented Method :
<?php
$mysqli = new mysqli("localhost", "root", "", "Mydb");
if($mysqli === false){
die("ERROR: Could not connect. ". $mysqli->connect_error);
}
$sql = "UPDATE data SET Age='28' WHERE id=201";
if($mysqli->query($sql) === true){
echo "Records was updated successfully.";
} else{
echo "ERROR: Could not able to execute $sql. ". $mysqli->error;
}
$mysqli->close();
?>
Update Query using PDO Method :
<?php
try{
$pdo = new PDO("mysql:host=localhost; dbname=Mydb", "root", "");
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e){
die("ERROR: Could not connect. " . $e->getMessage());
}
try{
$sql = "UPDATE data SET Age='28' WHERE id=201";
$pdo->exec($sql);
echo "Records was updated successfully.";
} catch(PDOException $e){
die("ERROR: Could not able to execute $sql. " . $e->getMessage());
}
unset($pdo);
?>
Thank You

You might also like