WP Chapter Six
WP Chapter Six
WP Chapter Six
2
PHP Connect to MySQL
The first step for interacting with MySQL connecting to the
server requires the appropriately named mysqli_connect( )
function:
» $dbc = mysqli_connect (hostname, username, password,
db_name);
The first three arguments sent to the function (hostname,
username, and password) are based upon the users and
privileges established within MySQL.
The fourth argument is the name of the database to use. This is
the equivalent of saying USE databasename within the mysql
client.
If the connection was made, the $dbc variable, short for
database connection (but you can use any name you want, of
course). 3
Connecting…
Most of the PHP functions for working with MySQL will take
this variable as its first argument.
If a connection problem occurred, you can call
mysqli_connect_error( ), which returns the connection error
message.
It takes no arguments, so would be called using just
» mysqli_connect_error( );
Set the MySQL host, username, password, and database
name as constants:
» DEFINE ('DB_USER', 'username');
» DEFINE ('DB_PASSWORD', 'password');
» DEFINE ('DB_HOST', 'localhost');
» DEFINE ('DB_NAME', 'sitename');
4
Connecting…
5
PHP Connect to MySQL…
Example: MySQLi Object-Oriented
PHP provides mysqli function to open a database connection.
Syntax: mysqli(server,username,password);
<?php
$servername = "localhost";
$username = "username";
$password = "password";
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>
6
PHP Connect to MySQL
Example: MySQLi Procedural
PHP provides mysqli_connect function to open a database
connection.
Syntax: mysqli_connect(servername,username,password);
<?php
$servername = "localhost";
$username = "username";
$password = "password";
// Create connection
$conn = mysqli_connect($servername, $username, $password);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
?>
7
PHP Connect to MySQL
Example: PDO (PHP Data Object)
PDO will work on 12 different database systems.
<?php
$servername = "localhost";
$username = "username";
$password = "password";
try {
$conn = new PDO("mysql:host=$servername;dbname=myDB", $username,
$password);
echo "Connected successfully";
} catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
?>
8
Open a Connection to MySQL
Database( summary)
Before we can access data in the MySQL database, we need to be
able to connect to the server.
PHP provides mysqli(), mysqli_connect() and PDO() function to
open a database connection.
Syntax example: $conn=mysqli_connect(server, user, password);
Server (Optional) :The host name running database server. If not
specified then default value is localhost.
User( Optional): The username accessing the database. If not
specified then default is the name of the user that owns the server
process. E.g root
Password(Optional ):The password of the user accessing the
database. If not specified then default is an empty password.
9
Closing a connection
The connection will be closed automatically when the script ends.
You can disconnect from MySQL database anytime using the
following PHP function.
$conn->close(); - for object oriented
mysqli_close($conn); - for procedural
$conn = null; - for PDO
10
Example: Connecting MySQL Server
<html><head>
<title>Connecting MySQL Server</title>
</head><body>
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$conn = mysqli_connect($dbhost, $dbuser, $dbpass);
if(! $conn ){
die('Could not connect: ' . mysqli_connect_error());
}else{
echo 'Connected successfully <br />';
}
mysqli_close($conn); //close connection
?> </body></html> 11
Create a MySQL Database
The CREATE DATABASE statement is used to create a database in MySQL.
Example: MySQLi Object-oriented
<?php // Create database
$servername = "localhost"; $sql = "CREATE DATABASE MAUDB";
$username = "root"; if ($conn->query($sql) === TRUE) {
$password = ""; echo "Database created successfully";
} else {
// Create connection echo "Error creating database: " .
$conn = new mysqli($servername, $conn->error;
$username, $password); }
// Check connection $conn->close();
if ($conn->connect_error) { ?>
die("Connection failed: " . $conn-
>connect_error);
}
12
Create a MySQL Database
Example: MySQLi Procedural
16
Selecting a Database using PHP Example
17
PHP MySQL Create Table
A database table has its own unique name and consists of columns
and rows.
The CREATE TABLE statement is used to create a table in
MySQL.
We will create a table named " student ", with five columns: "id",
"firstname", "lastname", "email" and "reg_date":
$sql=“CREATE TABLE student (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL,
email VARCHAR(50),
reg_date TIMESTAMP
) ”;
18
PHP MySQL Create Table
After the data type, you can specify other optional attributes for each column:
NOT NULL - Each row must contain a value for that column, null values are
not allowed.
DEFAULT value - Set a default value that is added when no other value is
passed.
UNSIGNED - Used for number types, limits the stored data to positive
numbers and zero.
AUTO INCREMENT - MySQL automatically increases the value of the field
by 1 each time a new record is added.
PRIMARY KEY - Used to uniquely identify the rows in a table. The column
with PRIMARY KEY setting is often an ID number, and is often used with
AUTO_INCREMENT.
Each table should have a primary key column (in this case: the "id" column). Its
value must be unique for each record in the table.
19
PHP MySQL Create Table Example
Example : MySQLi Object-oriented
<?php // sql to create table
$servername = "localhost"; $sql="CREATE TABLE student (
$username = "root"; id INT(6) UNSIGNED
AUTO_INCREMENT PRIMARY KEY,
$password = "";
firstname VARCHAR(30) NOT NULL,
$dbname = “MAUDB"; lastname VARCHAR(30) NOT NULL,
// Create connection email VARCHAR(50),
$conn = new mysqli($servername, reg_date TIMESTAMP
$username, $password); ) ";
// Check connection if ($conn->query($sql) === TRUE) {
if ($conn->connect_error) { echo "Table student created successfully";
die("Connection failed: " . $conn- } else {
>connect_error); echo "Error creating table: " . $conn->error;
}
}
$conn->close();
//select DB ?>
mysqli_select_db($conn,
20
$dbname);
PHP MySQL Create Table Example
Example : MySQLi Procedural
<?php // sql to create table
$servername = "localhost"; $sql = "CREATE TABLE student (
$username = "root"; id INT(6) UNSIGNED AUTO_INCREMENT
$password = ""; PRIMARY KEY,
$dbname = “MAUDB"; firstname VARCHAR(30) NOT NULL,
// Create connection lastname VARCHAR(30) NOT NULL,
email VARCHAR(50),
$conn =
reg_date TIMESTAMP
mysqli_connect($servername, )";
$username, $password); if (mysqli_query($conn, $sql)) {
// Check connection echo "Table student created successfully";
if (!$conn) { } else {
echo "Error creating table: " . mysqli_error($conn);
die("Connection failed: " . } mysqli_close($conn);
mysqli_connect_error()); ?>
}
//select database
mysqli_select_db($conn, 21
PHP MySQL Create Table Example
Example : MySQLi Procedural
<?php // sql to create table
$servername = "localhost"; $sql = "CREATE TABLE student (
$username = "root"; id INT(6) UNSIGNED AUTO_INCREMENT
PRIMARY KEY,
$password = ""; firstname VARCHAR(30) NOT NULL,
$dbname = “MAUDB"; lastname VARCHAR(30) NOT NULL,
email VARCHAR(50),
try { reg_date TIMESTAMP )";
//Connect and select database // use exec()
$conn = new $conn->exec($sql);
PDO("mysql:host=$servername; echo "Table student created successfully";
dbname=$dbname", $username, } catch(PDOException $e) {
echo $sql . "<br>" . $e->getMessage();
$password); }
$conn = null;
?>
22
Dropping table using PHP
• It is very easy to drop an existing MySQL table but you need to
be very careful while deleting any existing table because data
lost will not be recovered after deleting a table.
• SQL syntax to drop a table
Syntax: DROP TABLE table_name ;
• To drop an existing table in any database you can use the PHP
mysqli_query() function.
Syntax: mysqli_query(connection ,sql ); // Sql represent drop
table query
23
Dropping table using PHP Example
Example : MySQLi Procedural
<?php //Select database
$servername = "localhost"; mysqli_select_db($conn, $dbname);
$username = "root"; // sql to create table
$password = ""; $sql = "drop TABLE student";
$dbname = “MAUDB";
if (mysqli_query($conn, $sql)) {
// Create connection echo "Table student droped
$conn = successfully";
mysqli_connect($servername, } else {
$username, $password); echo "Error creating table: " .
// Check connection mysqli_error($conn);
if (!$conn) { }
die("Connection failed: " . mysqli_close($conn);
mysqli_connect_error()); ?>
}
24
Inserting data into MySQL table
After a database and a table have been created, we can start adding data in the
table.
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
To add a new records into MySQL table we can use SQL INSERT INTO
command.
SQL syntax of INSERT INTO query
Syntax: INSERT INTO table_name ( field1, field2,..fieldN )
VALUES ( value1, value2,...valueN );
To insert a data in any table you can use the PHP query(), mysqli_query() and
exec() function.
Syntax: mysqli_query( connection,sql ); // Sql represent insert data query
25
Example: Insert a record in a table
Example : MySQLi Object-oriented
<?php //Select database
$servername = "localhost"; mysqli_select_db($conn, $dbname);
$username = "root"; //insert data query
$password = ""; $sql = "INSERT INTO student (firstname,
$dbname = “MAUDB"; lastname, email)
VALUES ('John’, Abel',
// Create connection '[email protected]')";
$conn = new if ($conn->query($sql) === TRUE) {
mysqli($servername, $username, echo "New record created
$password); successfully";
// Check connection } else {
if ($conn->connect_error) { echo "Error: " . $sql . "<br>" . $conn->error;
die("Connection failed: " . $conn- }
>connect_error);
} $conn->close();
?>
26
Example: Insert a record in a table
Example : MySQLi Procedural
<?php //Select database
$servername = "localhost"; mysqli_select_db($conn, $dbname);
$username = "root"; $sql = "INSERT INTO student (firstname,
$password = ""; lastname, email)
$dbname = “MAUDB"; VALUES ('ahmed', 'abebe',
'[email protected]')";
// Create connection
$conn = if (mysqli_query($conn, $sql)) {
mysqli_connect($servername, echo "New record created
$username, $password); successfully";
// Check connection } else {
if (!$conn) { echo "Error: " . $sql . "<br>" .
die("Connection failed: " . mysqli_error($conn);
mysqli_connect_error()); }
} mysqli_close($conn);
?>
27
Example: Insert a record in a table
Example : PDO
<?php $sql = "INSERT INTO student (firstname,
$servername = "localhost"; lastname, email)
$username = "root"; VALUES ('abebe', 'alemu',
$password = ""; '[email protected]')";
$dbname = “MAUDB"; // use exec()
$conn->exec($sql);
try { echo "New record created successfully";
$conn = new } catch(PDOException $e) {
PDO("mysql:host=$servername;d echo $sql . "<br>" . $e->getMessage();
bname=$dbname", $username, }
$password);
$conn = null;
?>
28
PHP MySQL Insert Multiple Records
Multiple SQL statements must be executed with the mysqli_multi_query()
function and each SQL statement must be separated by a semicolon.
Example: MySQLi Object-oriented
<?php $sql = "INSERT INTO student (firstname,
$servername = "localhost"; lastname, email) VALUES ('Hawa', 'Ahmed’,
$username = "root"; '[email protected]');";
$sql .= "INSERT INTO student (firstname,
$password = ""; lastname, email) VALUES ('Helen', 'Mohammed',
$dbname = “MAUDB"; '[email protected]');";
$sql .= "INSERT INTO student (firstname,
// Create connection lastname, email) VALUES ('Abel', 'Ephream',
$conn = new mysqli($servername, '[email protected]')";
$username, $password);
// Check connection if ($conn->multi_query($sql) === TRUE) {
echo "New records created successfully";
if ($conn->connect_error) { } else {
die("Connection failed: " . $conn- echo "Error: " . $sql . "<br>" . $conn->error;
>connect_error); }
}
//select Database $conn->close();
mysqli_select_db($conn,$dbname); ?>
29
PHP MySQL Insert Multiple Records…..
Multiple SQL statements must be executed with the mysqli_multi_query()
function and each SQL statement must be separated by a semicolon.
Example: MySQLi Procedural
$sql = "INSERT INTO student (firstname,
<?php lastname, email) VALUES ('Hawa', 'Ahmed',
$servername = "localhost"; '[email protected]');";
$username = "root"; $sql.= "INSERT INTO student (firstname,
$password = ""; lastname, email) VALUES ('Helen',
$dbname = "junedb"; 'Mohammed', '[email protected]');";
$sql.= "INSERT INTO student (firstname,
// Create connection lastname, email) VALUES ('Abel', 'Ephream',
$conn = mysqli_connect($servername, '[email protected]')";
$username, $password);
// Check connection if (mysqli_multi_query($conn,$sql)) {
if (!$conn) { echo "New records created successfully";
die("Connection failed: " . } else {
$mysqli_connect_error); echo "Error: " . $sql . "<br>" .
} $mysqli_error($conn);
//select database }
mysqli_select_db($conn,$dbname); $conn->close();
?> 30
PHP MySQL Insert Multiple Records…..
The PDO way is a little bit different, it use different functions.
Example: PDO
// SQL statements
$conn->exec("INSERT INTO student (firstname,
<?php lastname, email) VALUES ('John', 'Alex',
$servername = "localhost"; '[email protected]')");
$username = "root"; $conn->exec("INSERT INTO student (firstname,
$password = ""; lastname, email) VALUES ('Hayat', 'Ahmed',
$dbname = “MAUDB"; '[email protected]')");
$conn->exec("INSERT INTO student (firstname,
try { lastname, email) VALUES ('Abebe', 'kebede',
'[email protected]')");
$conn = new
PDO("mysql:host=$servername;dbname // commit the transaction/save the transaction
=$dbname", $username, $password); $conn->commit();
// begin the transaction echo "New records created successfully";
$conn->beginTransaction(); } catch(PDOException $e) {
// roll back the transaction if something failed
$conn->rollback();
echo "Error: " . $e->getMessage();
}
$conn = null;
?>
31
Example: Insert a record in a table from HTML form
<html><head>
<title>Insert a record</title>
</head><body>
<?php
// tests if a variable has a value (including 0, FALSE, or an empty string, but not NULL).
if(isset($_POST['add']))
{
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$dbname = ‘MAUDB';
$conn = mysqli_connect($dbhost, $dbuser, $dbpass);
if(!$conn){
die('Could not connect: ' . mysqli_connect_error());
}
Cont..
if ($_SERVER["REQUEST_METHOD"] == "POST"){
$student_Name = $_POST['student_Name'];
$student_Email = $_POST['student_Email'];
}
$sql = "INSERT INTO student (firstname, email)VALUES
('$student_Name',' ','$student_Email')";
mysqli_select_db($conn,$dbname);
$retval = mysqli_query( $conn,$sql );
if(!$retval ) {
die('Could not enter data: ' . mysqli_connect_error()); }
echo "Data entered successfully\n";
mysqli_close($conn);
} ?>
Cont..
40
Select data from DB using PDO
<?php if ($stmt->rowCount() > 0) {
$servername = "localhost"; // Output data of each row
$username = "root"; while ($row = $stmt-
>fetch(PDO::FETCH_ASSOC)) {
$password = "";
echo "<tr>";
$dbname = "junedb"; echo "<td style='border: 1px solid black;
try { padding: 8px;'>".$row["id"] . "</td>";
// Create a new PDO instance echo "<td style='border: 1px solid black;
$conn = new padding: 8px;'>" . $row["firstname"] . " " .
PDO("mysql:host=$servername;dbname= $row["lastname"] . "</td>";
echo "</tr>";
$dbname", $username, $password);
}
// SQL query to select data } else {
$sql = "SELECT id, firstname, echo "<tr><td colspan='2' style='border:
lastname, email FROM student"; 1px solid black; padding: 8px; text-align:
$stmt = $conn->prepare($sql); center;'>0 results</td></tr>";
$stmt->execute(); }
echo "</table>";
// Start HTML output
echo "</body></html>";
echo "<html><body>"; } catch (PDOException $e) {
echo "<table style='border- echo "Connection failed: " . $e-
collapse: collapse; border: 1px >getMessage();
solid black;'>"; }
echo "<tr><th style='border: // Close connection
$conn = null;
1px solid black; padding:
?>
8px;'>ID</th>
<th style='border: 1px solid 41
Using WHERE clause
We have seen SQL SELECT command to fetch data from MySQL table. We
can use a conditional clause called WHERE clause to filter out results.
Using WHERE clause we can specify a selection criteria to select required
records from a table.
Here is generic SQL syntax of SELECT command with WHERE
42
Updating data using PHP
There may be a requirement where existing data in a MySQL table need
to be modified.
The UPDATE statement is used to update existing records in a table
This will modify any field value of any MySQL table
SQL syntax of UPDATE command
Syntax:UPDATE table_name SET field1=new-value1, field2=new-
value2 [WHERE Clause];
You can update one or more field all together and You can also
specify any condition using WHERE clause.
You can update values in a single table at a time.
The WHERE clause is very useful when you want to update selected
rows in a table.
You can use SQL UPDATE command with or without WHERE CLAUSE
into PHP function query() in OOP, mysqli_query() in procedural and
prepare() in PDO.
43
Updating data using MySQLi Object-
oriented style
<?php
$servername = $sql = "UPDATE student SET
"localhost"; firstname=‘mohamed',
$username = "root"; lastname=‘Awol' WHERE id=3";
$password = "";
$dbname = “MAUDB"; if ($conn->query($sql) ===
TRUE) {
// Create connection echo "Record updated
$conn = new successfully";
mysqli($servername, } else {
$username, $password, echo "Error updating
$dbname); record: " . $conn->error;
// Check connection }
if ($conn->connect_error) $conn->close();
{ ?>
die("Connection failed:
" . $conn- 44
Updating data using MySQLi Procedural
style
<?php $sql = "UPDATE student SET
$servername = lastname=‘Abebe' WHERE id=3";
"localhost";
$username = "root"; if (mysqli_query($conn,
$password = ""; $sql)) {
$dbname = “MAUDB"; echo "Record updated
successfully";
// Create connection } else {
$conn = echo "Error updating
mysqli_connect($servernam record: " .
e, $username, $password, mysqli_error($conn);
$dbname); }
// Check connection
if (!$conn) { mysqli_close($conn);
die("Connection failed: ?>
" .
mysqli_connect_error()); 45
Updating data using PDO style
<?php // Prepare statement
$servername = $stmt = $conn-
"localhost"; >prepare($sql);
$username = "root";
$password = ""; // execute the query
$dbname = “MAUDB"; $stmt->execute();
try { // echo a message to say
$conn = new the UPDATE succeeded
PDO("mysql:host=$serverna echo $stmt->rowCount() . "
me;dbname=$dbname", records UPDATED
$username, $password); successfully";
} catch(PDOException $e) {
$sql = "UPDATE student echo $sql . "<br>" . $e-
SET lastname='Abel' WHERE >getMessage();
id=3"; }
$conn = null;
?> 46
PHP MySQL Delete Data
If you want to delete a record from any MySQL table then you can
use SQL command DELETE FROM.
SQL syntax of DELETE command
Syntax: DELETE FROM table_name [WHERE Clause];
If WHERE clause is not specified then all the records will be
deleted from the given MySQL table.
You can specify any condition using WHERE clause.
You can delete records in a single table at a time.
The WHERE clause is very useful when you want to delete
selected rows in a table.
You can use SQL DELETE command with or without WHERE
CLAUSE into PHP function query() in OOP, mysqli_query() in
procedural and exec() in PDO. 47
Delete Data using MySQLi Object-oriented
$conn = null;
?>
50
PHP MySQL like Clauses
A WHERE clause with equal sign (=) works fine where we want to do an exact
match.
The LIKE operator is used in a WHERE clause to search for a specified
pattern in a column.
SQL syntax of SELECT command
Syntax: SELECT field1, field2,...fieldN from table_name1,
table_name2...WHERE field1 LIKE condition1 [AND [OR]] filed2 = 'somevalue'
You can use LIKE clause along with WHERE clause in place of equal sign.
When LIKE is used along with % sign then it will work like a meta character
search (used to define wildcards (missing letters) both before and after the
pattern).
%et%-Return all the records from the table for which the student name
contains ”et”.
%et-return all records from the table for which student name ends with
“et”.
et%-return all records from the table for which student name begins with
“et”. 51
PHP MySQL Delete Data like Clauses
example
<?php $sql = "SELECT id, firstname,
$servername = "localhost"; lastname FROM student where
$username = "root"; firstname like '%hn%'";
$result = mysqli_query($conn,
$password = "";
$sql);
$dbname = “MAUDB";
if (mysqli_num_rows($result) > 0)
// Create connection {
$conn = // output data of each row
mysqli_connect($servername, while($row =
$username, $password, mysqli_fetch_assoc($result)) {
$dbname); echo "id: " . $row["id"]. " ,
Name: " . $row["firstname"]. " " .
// Check connection
$row["lastname"]. "<br>";
if (!$conn) { }
die("Connection failed: " . } else {
mysqli_connect_error()); echo "0 results";
} }
mysqli_close($conn);
?> 52
Using ORDER BY clause
We have seen SQL SELECT command to fetch data from MySQL table.
When you select rows, the MySQL server is free to return them in
any order, unless you instruct it otherwise by saying how to sort the
result.
But you sort a result set by adding an ORDER BY clause that names
the column or columns you want to sort by.
SQL syntax of SELECT command along with ORDER BY
Syntax:SELECT field1, field2,...fieldN table_name1, table_name2
ORDER BY field1, [field2...] [ASC [DESC]]
You can sort returned result on any field provided that filed is being
listed out.
You can sort result on more than one field.
You can use keyword ASC or DESC to get result in ascending or
descending order. By default its ascending order.
You can use WHERE...LIKE clause in usual way to put condition.
53
Using order Clauses example
<?php $sql = "SELECT id, firstname,
$servername = "localhost"; lastname FROM student ORDER BY
$username = "root"; firstname";
$result = mysqli_query($conn,
$password = "";
$sql);
$dbname = "junedb";
if (mysqli_num_rows($result) > 0)
// Create connection {
$conn = // output data of each row
mysqli_connect($servername, while($row =
$username, $password, mysqli_fetch_assoc($result)) {
$dbname); echo "id: " . $row["id"]. " ,
Name: " . $row["firstname"]. " " .
// Check connection
$row["lastname"]. "<br>";
if (!$conn) { }
die("Connection failed: " . } else {
mysqli_connect_error()); echo "0 results";
} }
mysqli_close($conn);
?> 54
!! ?
n d ?
e ns
h e i o
T es t
u
Q
55