8 Database Operations

Web Technology II · Unit 8

Database Operations

Exam-focused notes for Database Operations (Web Technology II, BIT301): what the TU syllabus asks and how it has actually been tested, with 5 solved past questions from this unit.

Database Operations in short

Most web applications keep data in a database. PHP connects to MySQL through the MySQLi extension or through PDO.

Database Operations: notes

Database connection creation

To use a database, PHP must connect with the host name, user, password and database name. MySQL is the usual choice, and PHP has two main ways to reach it: MySQLi (MySQL only) and PDO (many databases).

<?php
// MySQLi, object style
$conn = new mysqli("localhost", "root", "", "school");
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}
echo "Connected";
$conn->close();

Steps in any database program: connect, run a query, handle the result, close the connection.

MySQLi object interface

MySQLi (MySQL improved) works in two styles: procedural (mysqli_connect()) and object oriented (new mysqli()). The object interface uses methods of the mysqli object.

<?php
$db = new mysqli("localhost", "root", "", "school");
$db->set_charset("utf8mb4");

$result = $db->query("SELECT id, name FROM students");
echo $result->num_rows;
while ($row = $result->fetch_assoc()) {
    echo $row["id"] . " " . $row["name"] . " ";
}
$result->free();
$db->close();

Useful members:

  • $db->query($sql) runs a query and returns a result object.
  • $db->connect_error holds a connection error.
  • $db->error holds the last query error.
  • $db->insert_id gives the last auto-increment id.
  • $db->affected_rows gives the rows changed.
  • $db->prepare($sql) makes a prepared statement.
  • $db->real_escape_string() escapes text, but prepared statements are better.

What this unit covers

  • Database connection creation
  • MySQLi object interface
  • PHP Data Objects and PDO
  • Database querying and SQL execution
  • Data retrieval and display
  • Data insertion into tables
  • Data deletion from tables
  • Result set handling

Data deletion from tables

2082 · 5 marks

Consider you have student records in a database table. Now create a PHP page with delete button action and a text field. The button should delete a record if it matches the name of the student entered in the text field. Use your own assumption for the database table. [5]

The page works against a database school holding one table of students. Nothing about the design is unusual: a surrogate key, the student name, and two descriptive columns. id name age address ------------------------ 1 Ram Sharma 20 Kathmandu 2 Sita Thapa 21 Pokhara 3 Hari Poudel 19 Chitwan The ...

Open this answer on its own page →

PHP Data Objects and PDO

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.[10]

Show solved answer

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

PHP Data Objects

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.

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.

Open this answer on its own page →

Database connection creation

2080 · 10 marks

How can you create a database connection? Create a PHP form that includes text field, password field, radio button elements. Now write a function to insert the data in the fields into a database table.[10]

PHP does not talk to MySQL directly, it uses an extension. Two are current: MySQLi, which works with MySQL and MariaDB only, and PDO, which puts the same interface in front of a dozen database engines. Both open a connection from four pieces of information, the host, the database user, that user'...

Open this answer on its own page →

Database querying and SQL execution

2079 · 5 marks

How can you query a database in PHP? [5]

Querying a database from PHP always follows the same shape: open a connection to the server, hand it an SQL statement, and read back either a result set (for a SELECT) or a count of affected rows (for an INSERT, UPDATE or DELETE). Two extensions are current, MySQLi, which works with MySQL and Mar...

Open this answer on its own page →

Data retrieval and display

0 · 5 marks

Write a PHP program to connect database and retrieve data from a table and display in a page. [5]

A database collegedb holding a table of students: The script opens the connection, runs a SELECT, and renders the rows into an HTML table. The query text here is fixed, so query() is enough; if the page later filters by something the visitor typed, the statement would be prepared and the value bo...

Open this answer on its own page →