Chapter 9
Chapter 9
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’]
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', '[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]')";
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='bikila' WHERE id=3";
if (mysqli_query($conn, $sql)) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . mysqli_error($conn);
}