PHP Database

Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 22

PHP MySQL Database

Introduction to Database
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)

 Example (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"; ?>
 Close the connection
mysqli_close($conn);
PHP Connect to MySQL (OO)
<?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";
?>
PHP
<?php
Create a MySQL Database
$servername = "localhost";
$username = "username";
$password = "password";
// Create connection
$conn = mysqli_connect($servername, $username, $password);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
// 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);?>
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$conn = new mysqli($servername, $username, $password);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Create database
$sql = "CREATE DATABASE myDB";
if ($conn->query($sql) === TRUE) {
echo "Database created successfully";
} else {
echo "Error creating database: " . $conn->error;}
$conn->close();
<?php
PHP Create MySQL Tables
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
$conn = mysqli_connect($servername, $username, $password, $dbname);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());}
$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))";
if (mysqli_query($conn, $sql)) {
echo "Table MyGuests created successfully";
} else {
echo "Error creating table: " . mysqli_error($conn);
}
mysqli_close($conn);
?>
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);}
// 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)";
if ($conn->query($sql) === TRUE) {
echo "Table MyGuests created successfully";
} else {
echo "Error creating table: " . $conn->error;}
$conn->close();?>
Insert Data Into MySQL
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
$conn = mysqli_connect($servername, $username, $password,
$dbname);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$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);
?>
Insert Multiple Records

$sql = "INSERT INTO MyGuests (firstname, lastname, email)


VALUES ('John', 'Doe', '[email protected]');";
$sql .= "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('Mary', 'Moe', '[email protected]');";
$sql .= "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('Julie', 'Dooley', ‘[email protected]')";
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);}
$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', '[email protected]')";
if ($conn->query($sql) ==TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
PHP Prepared Statements
 A prepared statement is a feature used to execute the same (or
similar) SQL statements repeatedly with high efficiency.
 Prepared statements basically work like this:
1. Prepare: An SQL statement template is created and sent to the
database. Certain values are left unspecified, called parameters
(labeled "?"). Example: INSERT INTO MyGuests VALUES(?,
?, ?)
2. The database parses, compiles, and performs query
optimization on the SQL statement template, and stores the
result without executing it
3. Execute: At a later time, the application binds the values to the
parameters, and the database executes the statement. The
application may execute the statement as many times as it
wants with different values
 Compared to executing SQL statements directly, prepared
statements have three main advantages:
 Prepared statements reduce parsing time as the preparation on

the query is done only once (although the statement is


executed multiple times)
 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,

because parameter values, which are transmitted later using a


different protocol, need not be correctly escaped. If the
original statement template is not derived from external input,
SQL injection cannot occur.
Prepared Statements in MySQLi
<?php
$conn = new mysqli("localhost", “username”, "password", “myDB”);
// 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]";
$stmt->execute();
$firstname = "Mary";
$lastname = "Moe";
$email = "[email protected]";
$stmt->execute();
echo "New records created successfully";
$stmt->close();
$conn->close();?>
 In our SQL, we insert a question mark (?) where we want to substitute in
an integer, string, double or blob value.
 Then, have a look at the bind_param() function:
 $stmt->bind_param("sss", $firstname, $lastname, $email);
 This function binds the parameters to the SQL query and tells the database
what the parameters are. The "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

 By telling mysql what type of data to expect, we minimize the risk of SQL
injections.
 Note: If we want to insert any data from external sources (like user input),
it is very important that the data is sanitized and validated.
PHP
<?php
Select Data From MySQL(procedural)
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
$conn = mysqli_connect($servername, $username, $password, $dbname);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());}
$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);?>
PHP Select Data From MySQL(OO)
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);}
$sql = "SELECT id, firstname, lastname FROM MyGuests";
$result = $conn->query($sql);
if ($result->num_rows() > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " .
$row["lastname"]. "<br>“;}
} else {
echo "0 results";}
$conn->close();
mysqli_close($conn);?>
 The code in last slide explained below:
 First, we set up an SQL query that selects the id, firstname and
lastname columns from the table. The next line of code runs
the query and puts the resulting data into a variable called
$result.
 Then, the function num_rows() checks if there are more than
zero rows returned.
 If there are more than zero rows returned, the function
fetch_assoc() puts all the results into an associative array that
we can loop through. The while() loop loops through the result
set and outputs the data from the id, firstname and lastname
columns.
PHP Delete Data From MySQL(procedural)
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
$conn = mysqli_connect($servername, $username, $password, $dbname);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
// sql to delete a record
$sql = "DELETE FROM MyGuests WHERE id=3";
if (mysqli_query($conn, $sql)) {
echo "Record deleted successfully";
} else {
echo "Error deleting record: " . mysqli_error($conn);
}
mysqli_close($conn);?>
PHP Delete Data From MySQL(OO)
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . mysqli_connect_error());
}
// sql to delete a record
$sql = "DELETE FROM MyGuests WHERE id=3";
if ($conn->query($sql)) {
echo "Record deleted successfully";
} else {
echo "Error deleting record: " . $conn->error;
}
mysqli_close($conn);?>
PHP Update Data in MySQL
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
$conn = mysqli_connect($servername, $username, $password,dbname);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());}
$sql = "UPDATE MyGuests SET lastname='Doe' WHERE id=2";
if (mysqli_query($conn, $sql)) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . mysqli_error($conn);}
mysqli_close($conn); ?>
PHP Update Data in MySQL
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
?
?
?
Functions Covered
 mysqli_connect()
 mysqli_query()
 mysqli_num_rows()
 mysqli_fetch_assoc()
 mysqli_close()
 mysqli()
 Query()
 num_rows()
 fetch_assoc()
 prepare()
 bind_param()
 execute()
 get_result()

You might also like