You are on page 1of 31

CHAPTER 9

Connecting to Databases
Outline
 Introduction
 Connect to an existing Database
 Send Data to a Database
 Retrieve Data from a Database
 Modify Existing Data
 Remove Existing Data
Introduction
 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?
 PDO will work on 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.
…cont’d…
 Both are object-oriented, but MySQLi also offers a procedural
API.
 Both support Prepared Statements.
 Prepared Statements protect from SQL injection, and are very
important for web application security.
 The MySQLi extension is automatically installed in most
cases, when php5 mysql package is installed.
 For PDO installation details, go to: 
http://php.net/manual/en/pdo.installation.php
 Before we can access data in the MySQL database, we need to
be able to connect to the server
Connect to an existing Database
 MYSQLi Server Connection code (Object oriented)
<?php
$servername = "localhost:3306";
$username = "root";
$password = "";
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>
…cont’d…
 MYSQLi Server Connection code (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";
?>
…cont’d…
 PDO Server Connection code
<?php
$servername = "localhost";
$username = “root";
$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();   }
?>
…cont’d…
 In the PDO example above we have also specified a
database (myDB).
 PDO require a valid database to connect to. If no database is
specified, an exception is thrown.
 A great benefit of PDO is that it has an exception class to
handle any problems that may occur in our database queries.
 Close the connections as follows:
 $conn->close(); //mysqli object oriented
 $mysqli_close($conn); //mysqli procedural
 $conn=null; //PDO
Send Data to a Database
 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,...)
…cont’d…
 If a column is AUTO_INCREMENT (like the "id"
column) or TIMESTAMP (like the "reg_date"
column), it is no need to be specified in the SQL
query; MySQL will automatically add the value.
 In this discussion we will be following PDO style.
 Use the previous forms for practice with the codes
in here (after this point)
…cont’d…
 We will use the following info for our program
Name values in Form Variables in PHP

username $_POST[‘username’]
email $_POST[‘email’]
password1 $_POST[‘password1’]
password2 $_POST[‘password2’]
btnR $_POST[‘btnR’]

 Create an ‘account’ table in your xampp server


…cont’d…
 You may have the following kind of code in PDO
style
//receiving the data from the form
$un=$_POST['username'];
$e=$_POST['email'];
$pw1=$_POST['password1'];
$pw2=$_POST['password2'];
$role="user";
if($pw1==$pw2) $pw=$pw1;
else echo"The passwords didn't match";
//fire the insertion query here
$sql = "INSERT INTO account (id,username,email,password,role)
VALUES (DEFAULT,'$un', '$e', '$pw','$role')";
// use exec() because no results are returned
$conn->exec($sql);
echo “Registration completed successfully";
…cont’d…
 Knowing the last inserted value for auto increment
values is very important sometimes.
 We can do this as follows:
 $last_id = mysqli_insert_id($conn); //procedural
 $last_id = $conn->insert_id; //object oriented
 $last_id = $conn->lastInsertId(); //PDO style
 Multiple SQL statements must be executed with
the mysqli_multi_query() function.
…cont’d….
 Use the following syntax for mysqli procedural
$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', 'john@example.com');";
$sql .= "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('Mary', 'Moe', 'mary@example.com');";
$sql .= "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('Julie', 'Dooley', 'julie@example.com')";

if (mysqli_multi_query($conn, $sql)) {
    echo "New records created successfully";
} else {
    echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
…cont’d…
 Use the following syntax for mysqli object oriented
$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', 'john@example.com');";
$sql .= "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('Mary', 'Moe', 'mary@example.com');";
$sql .= "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('Julie', 'Dooley', 'julie@example.com')";

if ($conn->multi_query($sql) === TRUE) {


    echo "New records created successfully";
} else {
    echo "Error: " . $sql . "<br>" . $conn->error;
}
…cont’d…
 Use the following syntax for PDO
// begin the transaction
    $conn->beginTransaction();
    // our SQL statements
    $conn->exec("INSERT INTO MyGuests (firstname, lastname, email) 
    VALUES ('John', 'Doe', 'john@example.com')");
    $conn->exec("INSERT INTO MyGuests (firstname, lastname, email) 
    VALUES ('Mary', 'Moe', 'mary@example.com')");
    $conn->exec("INSERT INTO MyGuests (firstname, lastname, email) 
    VALUES ('Julie', 'Dooley', 'julie@example.com')");
    // commit the transaction
    $conn->commit();
    echo "New records created successfully";
// roll back the transaction if something failed
    $conn->rollback();
Retrieve Data from a Database
 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
 We can do data retrieval by using MYSQLi
procedural, object oriented or PDO
 Look at the following examples:
…cont’d…
 MYSQLi procedural for Data retrieval
$sql = "SELECT id, username, email FROM account";
$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"]. " - UserName: " . $row["username"]. "-
Email: " . $row["email"]. "<br>";
}
} else {
echo "0 results";
}
…cont’d…
 MYSQLi object oriented for Data retrieval
$$sql = "SELECT id, username, email FROM account";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - UserName: " . $row["username"]. "-
Email:" . $row["email"]. "<br>";
}
} else {
echo "0 results";
}
…cont’d…
 PDO style for Data retrieval
$sql="SELECT id, username, email FROM account";
$s=$conn->query($sql);
$s->setFetchMode(PDO::FETCH_ASSOC);
while($row = $s->fetch())
{
echo "id:".$row["id"]."- UserName:".$row["username"]."-
Email:".$row["email"]."<br>";
}
Modify Existing Data
 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 in the UPDATE syntax: 
 The WHERE clause specifies which record or records that
should be updated.
 If you omit the WHERE clause, all records will be updated!
 Refer to the examples in the next slides
…cont’d…
 Procedural and OO style for Update
$sql = "UPDATE account SET username=‘abc' WHERE id=3";

if (mysqli_query($conn, $sql)) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . mysqli_error($conn);
}

$sql = "UPDATE account SET email=‘abc@gmail.com' WHERE id=3";

if ($conn->query($sql) === TRUE) {


echo "Record updated successfully";
} else {
echo "Error updating record: " . $conn->error;
}
…cont’d…
 PDO style for Update
$sql="UPDATE account SET email=? where id=?";
$u=$conn->prepare($sql);
$u->execute([‘abc@gmail.com',2]);
if($u)
echo "Update succeeded!";
else
echo "Error during update";
Remove Existing Data
 The DELETE statement is used to delete records from
a table:
 DELETE FROM table_name
WHERE some_column = some_value
 Notice the WHERE clause in the DELETE syntax: 
 The WHERE clause specifies which record or records that
should be deleted.
 If you omit the WHERE clause, all records will be deleted!
 The following examples delete the record with id=3 in
the “account" table:
…cont’d…
 Procedural and OO style for Delete
// sql to delete a record
$sql = "DELETE FROM account WHERE id=3";
if (mysqli_query($conn, $sql)) {
    echo "Record deleted successfully";
} else {
    echo "Error deleting record: " . mysqli_error($conn);
}

// sql to delete a record


$sql = "DELETE FROM account WHERE id=3";
if ($conn->query($sql) === TRUE) {
    echo "Record deleted successfully";
} else {
    echo "Error deleting record: " . $conn->error;
}
…cont’d…
 PDO style for delete
$sql=" DELETE FROM account WHERE id=?";
$u=$conn->prepare($sql);
$u->execute([2]);
if($u)
echo “Delete succeeded!";
else
echo "Error during delete";
Data base security using server side scripting

 SQL Injection is one of the most dangerous


vulnerabilities a web application can be prone to.
 When user input is being passed as part of an SQL
query it means that the user can manipulate the
query itself and force it to return a different result
to what it was supposed to return.
 In the following example the article parameter is
being insecurely passed to the query:
…cont’d…
 $articleid = $_GET['article']; $query = "SELECT *
FROM articles WHERE articleid = '$articleid'";
 A user can send a specially crafted value which will
be included in the SQL query before it is executed.
An example would be: 
 $query = "SELECT * FROM articles WHERE
articleid = '1'+union+select+1,version(),3''";
 Now the attacker with a few more requests can
enumerate all the tables/columns of the database and
exfiltrate sensitive information.
…cont’d…
 The solution to this problem is to use
parameterized SQL queries (prepared statements).
 By using parameterized queries,
 we essentially let the database know which part is the
query and which is the data (user input) by sending
them in two separate requests,
 thus eliminating the possibility of mixing user input
and the SQL query.
 The query can be rewritten as follows:
…cont’d…
 $query = "SELECT * FROM articles WHERE
articleid = '$articleid'";
will become
 $query = "SELECT * FROM articles WHERE
articleid = ?";
Or
 $query = "SELECT * FROM articles WHERE
articleid = :articleid";
The End

You might also like