2081 3

BIT301 ยท 2081 ยท 10 marks

What is a PHP Data Object? How does MySQLi Object Interface work? Write a PHP program to read data elements from a database table and display in a page.

What is a PHP Data Object? How does MySQLi Object Interface work? Write a PHP program to read data elements from a database table and display in a page.[10]

Web Technology IIChapter 8: Database OperationsPHP Data Objects and PDO

Quick answer

PDO is a database access layer that gives PHP one uniform, object oriented interface over many database engines: MySQL and MariaDB, PostgreSQL, SQLite, SQL Server, Oracle and others. The engine is named only in the DSN, the connection string, so moving an application from MySQL to PostgreSQL changes that one line rather than every call in the program.

PDO, the MySQLi object interface, and reading a table into a page

PHP Data Objects

Its strengths are worth naming. It is driver independent. It supports prepared statements with named placeholders, which keeps a statement readable when it carries five or six values. It can be told to report every failure as an exception, so a mistyped query cannot pass unnoticed. And with ATTR_EMULATE_PREPARES set to false, placeholders really are sent to the server as placeholders, rather than being substituted by the driver in PHP first.

<?php
$pdo = new PDO(
    'mysql:host=localhost;dbname=college;charset=utf8mb4',
    'root',
    '',
    [
        PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_EMULATE_PREPARES   => false,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
    ]
);

$stmt = $pdo->prepare('SELECT id, name, age, email FROM students WHERE age >= :age');
$stmt->execute([':age' => 20]);
$students = $stmt->fetchAll();
PDOMySQLi
Databases supportedTwelve driversMySQL and MariaDB only
API styleObject oriented onlyObject oriented and procedural
Prepared statementsYesYes
Named placeholdersYesNo, positional ? only
Binding a valueexecute([...]) or bindValue()bind_param() with a type string

Both are safe extensions and either is a correct choice. What matters far more than the choice between them is that user supplied values are bound rather than pasted into the SQL text.

How the MySQLi object interface works

MySQLi exposes the same functionality twice, as procedural functions and as objects. In the object interface the connection is an instance of mysqli, a query returns an instance of mysqli_result, and a prepared statement is an instance of mysqli_stmt. The work is then done by calling methods on those objects and reading their properties.

The connection object is created with the host, user, password and database name, and it is worth switching error reporting on first so that a failure raises an exception instead of returning false and letting the script continue:

<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

$conn = new mysqli('localhost', 'root', '', 'college');
$conn->set_charset('utf8mb4');

Calling $conn->query($sql) on a statement whose text is fixed returns a result object, and that object is asked for its rows, one at a time with fetch_assoc() or all at once with fetch_all(MYSQLI_ASSOC), and for how many there are through the num_rows property. When any part of the statement comes from the request, $conn->prepare($sql) returns a statement object instead, bind_param() attaches the values with a type string (s string, i integer, d float, b blob), execute() runs it and get_result() hands back the same kind of result object:

<?php
$stmt = $conn->prepare('SELECT id, name, age, email FROM students WHERE age >= ?');
$stmt->bind_param('i', $minimumAge);
$stmt->execute();
$students = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
$stmt->close();
MemberWhat it gives you
new mysqli(host, user, pass, db)The connection object
$conn->connect_errorThe failure message, if the connection could not be made
$conn->query($sql)Runs a fixed statement, returns a mysqli_result
$conn->prepare($sql)Compiles a statement with ? placeholders, returns a mysqli_stmt
$stmt->bind_param(), $stmt->execute()Supplies the values and runs the statement
$result->num_rowsNumber of rows in the result set
$result->fetch_assoc(), $result->fetch_all()Reads rows as associative arrays
$conn->affected_rows, $conn->insert_idThe effect of a write
$result->free(), $conn->close()Releases the result set and the connection

Reading a table and displaying it

The program assumes a database college with a table of students.

CREATE DATABASE college CHARACTER SET utf8mb4;
USE college;

CREATE TABLE students (
    id    INT AUTO_INCREMENT PRIMARY KEY,
    name  VARCHAR(100),
    age   INT,
    email VARCHAR(100)
);

INSERT INTO students (name, age, email) VALUES
('Ram Sharma',  20, '[email protected]'),
('Sita Thapa',  22, '[email protected]'),
('Hari Poudel', 21, '[email protected]');

The page finishes all its database work first and only then writes HTML, which keeps the two concerns apart and leaves the script free to send a header if it needs to.

<?php
// read_students.php
declare(strict_types=1);

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

$conn = new mysqli('localhost', 'root', '', 'college');
$conn->set_charset('utf8mb4');

$result   = $conn->query('SELECT id, name, age, email FROM students ORDER BY id');
$students = $result->fetch_all(MYSQLI_ASSOC);
$result->free();
$conn->close();

function e(?string $v): string
{
    return htmlspecialchars((string) $v, ENT_QUOTES, 'UTF-8');
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Student records</title>
    <style>
        body  { font-family: Arial, sans-serif; margin: 30px; }
        table { border-collapse: collapse; width: 70%; }
        th, td { border: 1px solid #aaa; padding: 10px; text-align: left; }
        th    { background: #4CAF50; color: #fff; }
        tr:nth-child(even) { background: #f2f2f2; }
    </style>
</head>
<body>

<h2>Student records from the database</h2>

<?php if ($students): ?>
    <table>
        <tr><th>ID</th><th>Name</th><th>Age</th><th>Email</th></tr>
        <?php foreach ($students as $row): ?>
            <tr>
                <td><?= (int) $row['id'] ?></td>
                <td><?= e($row['name']) ?></td>
                <td><?= (int) $row['age'] ?></td>
                <td><?= e($row['email']) ?></td>
            </tr>
        <?php endforeach; ?>
    </table>
<?php else: ?>
    <p>No records found in the students table.</p>
<?php endif; ?>

</body>
</html>

Every text column is printed through htmlspecialchars() and the numeric ones are cast to int. A value that came out of the database is not trustworthy simply because it was stored: a name typed as <script>alert(1)</script> would run in the browser of everyone who loaded this page if it were echoed raw, which is stored cross site scripting.

In summary

PDO is the portable extension, one object oriented API in front of many database drivers, with named placeholders and exceptions. MySQLi is MySQL specific and exposes the same work through a connection object, a result object and a statement object, whose methods do the querying and fetching. The program above uses that object interface end to end, running a fixed SELECT through query(), reading the rows with fetch_all(), and escaping every value on the way into the page. As soon as the page grows a filter that the visitor supplies, the query() call becomes a prepare() with a bound parameter, because a value from the request must never become part of the query text.

Short on time? The 1, 5 and 10 mark versions of this answer, flashcards and practice sets come with a program pass.