Web2 Lec5
Web2 Lec5
Database in php
Lec 5
Mohammed Sultan
1
Outlines
• What is Mysql?
• PHP Connect to MySQL
• Database Queries
• Prepared Statements
• Stored Procedures
2
PHP
• you can connect to and manipulate databases.
3
What is MySQL?
• MySQL is a database system used on the web
• MySQL is a database system that runs on a
server
• MySQL is ideal for both small and large
applications
• MySQL is very fast, reliable, and easy to use
• MySQL uses standard SQL
• MySQL compiles on a number of platforms
• MySQL is free to download and use
4
What is MySQL?
• The data in a MySQL database are stored in
tables. A table is a collection of related data,
and it consists of columns and rows.
5
PHP + MySQL Database System
• PHP combined with MySQL are cross-
platform.
6
Should I Use MySQLi or PDO?
• PDO will work on 12 different database
systems, whereas MySQLi will only work with
MySQL databases.
7
Should I Use MySQLi or PDO?
• In this, and in the following chapters we
demonstrate three ways of working with PHP
and MySQL:
• MySQLi (object-oriented)
• MySQLi (procedural)
• PDO
8
Dual procedural and object-oriented
interface
• The mysqli extension features a dual interface. It supports the
procedural and object-oriented programming paradigm.
• Users migrating from the old mysql extension may prefer the
procedural interface.
9
Database Queries
• A query is a question or a request.
• We can query a database for specific
information and have a recordset returned.
– SELECT * FROM students;
10
Dealing with forms
• HTML Forms (GET and POST)
• form is submitted to a PHP script
• information from that form is automatically made
available to the script
– forms.php
11
Steps for dealing with DB
• Connect to the MySQL server
– $connection = mysql_connect("localhost",
$username, $password);
• Access the database
– mysql_select_db("moh", $connection);
• Perform SQL operations
• Disconnect from the server
– mysql_close($connection);
12
Connect to the MySQL
(MySQLi Procedural)
<?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";
?>
14
Error Handling examples
if (!($connection =
mysql_connect("localhost",$name,$passwd)))
die("Could not connect");
function showerror()
{
die("Error " . mysql_errno() . " : " . mysql_error());
}
if (!(mysql_select_db("winestor", $connection)))
showerror();
15
PHP Create a MySQL Database
• Grant special CREATE privileges to create or to delete a MySQL
database.
• The CREATE DATABASE statement is used to create a database
in MySQL.
// Create database
$sql = "CREATE DATABASE myDB";
if (mysqli_query($conn, $sql)) {
echo "Database created successfully";
} else {
echo "Error creating database: " . mysqli_error($conn);
}
mysqli_close($conn);
16
?>
Building a Query
• Directly
– $query = 'select * from wines’;
17
PHP MySQL Select Data
• The SELECT statement is used to select data
from one or more tables
18
$sql = "SELECT id, firstname, lastname FROM MyGuests";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. "
" . $row["lastname"]. "<br>";
}
} else {
echo "0 results";
}
mysqli_close($conn);
?>
19
PHP MySQL Select Data
• the function num_rows() checks if there are
more than zero rows returned.
20
Running a Query
• mysql_query returns a result handle
– $result = mysqli_query($query, $connection)
21
Printing the Complete Row
• By number
for ($i=0; $i<mysql_num_fields($result); $i++)
echo $row[$i] . " ";
• By field
echo $row['surname'] . ' ' . $row['city'];
22
PHP MySQL Create Table
• The CREATE TABLE statement is used to create a table
in MySQL.
23
// sql to create table
$sql = "CREATE TABLE MyGuests (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL,
email VARCHAR(50),
reg_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE
CURRENT_TIMESTAMP
)";
if (mysqli_query($conn, $sql)) {
echo "Table MyGuests created successfully";
} else {
echo "Error creating table: " . mysqli_error($conn);
}
mysqli_close($conn);
?>
24
Inserting Into a Database
• Collect data from a form
• Validate data (JavaScript, PHP or both)
• Create a query
• Run the query
– mysql_query($query, $db);
25
Inserting Into a Database
$sql = "INSERT INTO MyGuests (firstname,
lastname, email)
VALUES ('John', 'Doe', '[email protected]')";
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" .
mysqli_error($conn);
}
mysqli_close($conn);
?>
26
Inserting Into a Database
• Multiple SQL statements must be executed
with the mysqli_multi_query() function.
27
Prepared Statements
• The MySQL database supports prepared statements.
28
Prepared Statements
• The MySQL server supports using anonymous,
positional placeholder with ?.
29
/* Non-prepared statement */
$mysqli->query("DROP TABLE IF EXISTS test");
$mysqli->query("CREATE TABLE test(id INT, label
TEXT)");
/* Prepared statement, stage 1: prepare */
$stmt = $mysqli->prepare("INSERT INTO test(id, label)
VALUES (?, ?)");
/* Prepared statement, stage 2: bind and execute */
$id = 1;
$label = 'PHP';
$stmt->bind_param("is", $id, $label); // "is" means that
$id is bound as an integer and $label as a string
$stmt->execute();
30
MySQL Limit Data Selections
• 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. Returning a large number of records can impact
on performance.
31
Stored Procedures
• The MySQL database supports stored procedures.
array(1) {
["id"]=>
string(1) "1"
} 33
• https://www.php.net/manual/en/mysqli.quick
start.stored-procedures.php
34
Any Questions?
35