How unit 5 is examined
This unit covers connecting PHP to MySQL and running database commands from PHP; the marks sit in the connection program, phpMyAdmin with database errors, and query execution.
Basic commands with PHP examples
Low weight
Definition. The basic commands are the PHP statements that talk to MySQL: connect, run an SQL string, read the result and close. A PHP application such as a shopping cart uses them together with sessions.
Key points.
- PHP sends every SQL command as a string through
mysqli_query(), so the same function creates, inserts, updates and deletes. - A shopping cart needs two tables:
products(id, name, price)andcart(id, session_id, product_id, qty). session_start()at the top of each page gives every visitor a session id that ties cart rows to that visitor.- The flow is: list products, add to cart, view cart, remove item.
Example.
<?php // cart.php
session_start(); $c = mysqli_connect("localhost","root","","shop");
$sid = session_id();
if (isset($_GET['add'])) // add to cart
mysqli_query($c, "INSERT INTO cart(session_id,product_id,qty) VALUES('$sid',".(int)$_GET['add'].",1)");
if (isset($_GET['del'])) // remove from cart
mysqli_query($c, "DELETE FROM cart WHERE id=".(int)$_GET['del']." AND session_id='$sid'");
$r = mysqli_query($c, "SELECT cart.id,name,price FROM cart JOIN products ON products.id=product_id WHERE session_id='$sid'");
while ($row = mysqli_fetch_assoc($r)) // view cart
echo $row['name']." - ".$row['price']." <a href='?del=".$row['id']."'>Remove</a><br>";
Asked: [7 marks] (Nov 2023) Create a simple shopping cart application using PHP and MySQL.
Connection to server
High weight
Definition. PHP-MySQL connectivity means opening a link from a PHP script to the MySQL server with mysqli_connect(host, username, password, dbname), which returns a connection object used by every later call. ==The connectivity string is $conn = mysqli_connect("localhost", "root", "", "college"); and it must be followed by a check for failure.==
Diagram.
Key points.
hostis the server address, normallylocalhostwhen PHP and MySQL run on the same machine.usernameandpasswordare the MySQL account credentials; XAMPP's default is userrootwith an empty password.dbnameis the database to select at connect time; it is optional, andmysqli_select_db()can choose it later.- PHP offers two APIs,
mysqli(procedural or object style, MySQL only) andPDO(many databases, uses a DSN string). - Connection errors are detected by testing the return value:
mysqli_connect()givesfalseon failure andmysqli_connect_error()returns the reason. - After the work is done the link is closed with
mysqli_close($conn). - The database operations insert, select, update and delete are all run over this one connection with
mysqli_query().
Example.
<?php
$conn = mysqli_connect("localhost", "root", "", "college");
if (!$conn) { die("Connection failed: " . mysqli_connect_error()); }
echo "Connected successfully"; // output: Connected successfully
mysqli_query($conn, "INSERT INTO student(name) VALUES('Ravi')");
$r = mysqli_query($conn, "SELECT * FROM student");
while ($row = mysqli_fetch_assoc($r)) { echo $row['name']; }
mysqli_close($conn);
PDO form:
<?php
try { $pdo = new PDO("mysql:host=localhost;dbname=college", "root", "");
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); }
catch (PDOException $e) { die("Failed: " . $e->getMessage()); }
Answer frame. Open with the definition and the connectivity string; draw the flow figure; then develop the four parameters, error check, one query on the connection (insert, select, update, delete), and close; close with the complete program and its output "Connected successfully". For the "operations" question add a one-line example each of INSERT, SELECT, UPDATE and DELETE.
Pitfall: Writing
mysql_connect(removed in PHP 7) instead ofmysqli_connect, or omitting the failure check.
Asked: [7 marks] (Jun 2020, Nov 2022, Dec 2024, Jun 2025) Write the connectivity string in PHP with MySQL database; write a MySQL connectivity program using PHP; list the statements used to connect PHP with MySQL with an example; how to establish a connection to a MySQL database using PHP. Asked: [7 marks] (Dec 2025) Explain PHP-MySQL connectivity and database operations.
Creating database
Not asked since 2022
Definition. Creating a database means running the SQL command CREATE DATABASE name from PHP.
Key points.
- The connection is made without a
dbname, because the database does not exist yet. - The command is sent with
mysqli_query($conn, "CREATE DATABASE college"), which returnstrueon success. - On failure,
mysqli_error($conn)gives the reason, for example that the database already exists.
Selecting a database
Not asked since 2022
Definition. Selecting a database makes one database the current one for all later queries, using mysqli_select_db($conn, "college").
Key points.
- It returns
trueorfalse, so it is tested like a connection. - Passing
dbnameas the fourth argument ofmysqli_connect()does the same in one step. - The SQL equivalent is
USE college.
Listing database
Not asked since 2022
Definition. Listing databases shows every database on the server, using the query SHOW DATABASES.
Key points.
- Run
$r = mysqli_query($conn, "SHOW DATABASES");and read the rows in a loop. - Each row is fetched with
mysqli_fetch_row($r)and the name is in$row[0]. - The account only sees the databases it has privileges on.
Listing table names
Not asked since 2022
Definition. Listing table names shows all tables of the selected database, using SHOW TABLES.
Key points.
- A database must be selected first, or the query fails.
mysqli_query($conn, "SHOW TABLES")returns one row per table with the name in$row[0].SHOW TABLESis the SQL form;DESCRIBE tablenamethen lists the columns of one table.
Creating a table
Not asked since 2022
Definition. Creating a table defines its columns and types with CREATE TABLE, sent through mysqli_query().
Key points.
- Example:
CREATE TABLE student(id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(50), marks INT). - Each column has a name, a data type and optional constraints such as
PRIMARY KEYandNOT NULL. - The database must be selected first, and the call returns
truewhen the table is made.
Inserting data
Not asked since 2022
Definition. Inserting data adds a row to a table with INSERT INTO table(columns) VALUES(values).
Key points.
- Example:
mysqli_query($conn, "INSERT INTO student(name,marks) VALUES('Ravi',80)"). - String values sit inside single quotes and numbers do not.
mysqli_affected_rows($conn)returns 1 after a successful insert, andmysqli_insert_id($conn)gives the new AUTO_INCREMENT id.- User input should go through a prepared statement to prevent SQL injection.
Altering tables
Not asked since 2022
Definition. Altering a table changes its structure with ALTER TABLE, run through mysqli_query().
Key points.
- Add a column:
ALTER TABLE student ADD email VARCHAR(50). - Remove a column:
ALTER TABLE student DROP COLUMN email. - Change a type:
ALTER TABLE student MODIFY marks FLOAT. - It changes the structure only, while
UPDATEchanges the data in rows.
Queries
Medium weight
Definition. Querying from PHP means sending an SQL statement to MySQL with mysqli_query() and then reading its result. A query is executed in five steps: connect, select the database, execute the query, fetch the result, and close the connection.
Steps.
Step 1: $conn = mysqli_connect("localhost","root","","college"); // connect and select DB
Step 2: if (!$conn) die(mysqli_connect_error()); // check the connection
Step 3: $r = mysqli_query($conn, "SELECT * FROM student"); // execute the query
Step 4: while ($row = mysqli_fetch_assoc($r)) echo $row['name']; // fetch row by row
Step 5: mysqli_close($conn); // close
Key points.
mysqli_query()returns a result object for SELECT andtrueorfalsefor INSERT, UPDATE and DELETE.- Rows are read with
mysqli_fetch_assoc()(column names),mysqli_fetch_row()(numbers) ormysqli_fetch_array()(both). mysqli_num_rows($r)counts the rows returned by a SELECT, andmysqli_affected_rows($conn)counts rows changed by INSERT, UPDATE or DELETE.- Example statements:
INSERT INTO student(name,marks) VALUES('Ravi',80),UPDATE student SET marks=90 WHERE name='Ravi',DELETE FROM student WHERE name='Ravi'. mysqli_prepare()withbind_param()(or PDOprepare()) runs the query with placeholders and is the safe method for user input.- Every call is followed by a check,
if (!$r) echo mysqli_error($conn);, to handle errors.
Answer frame. Open with the definition of a query; write the five steps; show one SELECT program; then one line each for INSERT, UPDATE and DELETE with mysqli_affected_rows; close with the error check and mysqli_close.
Asked: [7 marks] (Nov 2023, Jun 2025) Explain the steps in the PHP code for querying a database with suitable examples; explain how to execute SQL queries in PHP to retrieve, insert, update and delete data from a MySQL database.
Deleting database
Not asked since 2022
Definition. Deleting a database removes it and all its tables permanently with DROP DATABASE name.
Key points.
- It is run as
mysqli_query($conn, "DROP DATABASE college"). - The action cannot be undone, so a backup comes first.
DROP DATABASE IF EXISTS collegeavoids an error when the database is absent.
Deleting data and tables
Not asked since 2022
Definition. DELETE FROM table WHERE condition removes rows, and DROP TABLE name removes the whole table with its structure.
Key points.
- Without a
WHEREclauseDELETEremoves every row, though the table stays. DROP TABLE studentdeletes both the data and the table definition.mysqli_affected_rows($conn)tells how many rows were deleted.
PHPMyAdmin and database bugs
High weight
Definition. phpMyAdmin is a free, web-based tool written in PHP for administering MySQL through a browser, with no need to type SQL commands at a prompt. Database bugs are errors that occur when PHP talks to MySQL, such as connection failures, wrong SQL and constraint violations. phpMyAdmin manages MySQL through a browser; database bugs are handled by checking every call and using try-catch.
Key points (phpMyAdmin).
- phpMyAdmin comes bundled with XAMPP and WAMP and opens at
http://localhost/phpmyadmin. - It creates, alters and drops databases, tables and columns through forms.
- It inserts, edits, browses and deletes rows, and runs any SQL in its SQL tab.
- It imports and exports data (SQL, CSV) for backup and transfer.
- It manages users and privileges, and shows table structure, indexes and relations.
Key points (database bugs).
- Connection errors come from a wrong host, username, password or a stopped server;
mysqli_connect_error()reports them. - Query errors come from bad SQL syntax, a missing table or column, or a duplicate key;
mysqli_error($conn)reports them. - SQL injection is a security bug where unchecked user input changes the query, and prepared statements prevent it.
- Exceptions:
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT)or PDO'sERRMODE_EXCEPTIONthrows errors, and atry-catchblock handles them. - Errors should be logged with
error_log()and shown to the user as a plain message, never the raw SQL error.
Example.
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
try { $c = mysqli_connect("localhost","root","","college");
mysqli_query($c, "INSERT INTO student(id) VALUES(1)"); }
catch (mysqli_sql_exception $e) { error_log($e->getMessage()); echo "Something went wrong."; }
Answer frame. For "elucidate phpMyAdmin and bugs": define phpMyAdmin, list features 1-5, define bugs, explain the four bug types, and close with the fact that checking every call prevents most of them. For "handle errors and exceptions": open with the three error kinds, show mysqli_error, PDOException and the try-catch code, and close with logging.
Asked: [14 marks] (Nov 2022, Nov 2023, Dec 2025) Elucidate phpMyAdmin and briefly explain database bugs; short note on any two: a) phpMyAdmin and database bugs; explain the role of phpMyAdmin and handling database bugs. Asked: [7 marks] (Jun 2025) How do you handle database errors and exceptions in PHP?
Last-minute revision
- Connectivity string:
mysqli_connect("localhost","root","","dbname"), arguments host, user, password, database. - Failure check:
mysqli_connect_error()for connection,mysqli_error($conn)for queries. mysqli_query()runs any SQL; SELECT returns a result set, other statements return true or false.- Fetch functions:
mysqli_fetch_assoc,mysqli_fetch_row,mysqli_fetch_array; counts:mysqli_num_rows,mysqli_affected_rows. - Five query steps: connect, select DB, execute, fetch, close.
- SQL commands:
CREATE DATABASE,USE,SHOW DATABASES,SHOW TABLES,CREATE TABLE,INSERT,ALTER TABLE,DROP DATABASE,DELETE,DROP TABLE. DELETEremoves rows only;DROP TABLEremoves the table itself.- PDO uses a DSN
mysql:host=...;dbname=...andPDOException. - phpMyAdmin is a browser-based MySQL admin tool bundled with XAMPP.
- Shopping cart:
productsandcarttables plussession_start().
Memory hooks
- Connect argument order: "HUPD" (Host, User, Password, Database).
- Query steps: "C-S-E-F-C" (Connect, Select, Execute, Fetch, Close).
DELETEdeletes rows,DROPdrops the object.- Two error functions:
connect_errorfor the door,mysqli_errorfor the room. - phpMyAdmin is the "GUI face" of MySQL.
Coverage checklist
- Basic commandswith PHP examples: shopping cart application (Nov 2023).
- Connection to server: connectivity string and program (Jun 2020, Nov 2022, Dec 2024, Jun 2025), connectivity and operations (Dec 2025).
- creating database: CREATE DATABASE from PHP, no past question.
- selecting a database: mysqli_select_db, no past question.
- listing database: SHOW DATABASES, no past question.
- listing table names: SHOW TABLES, no past question.
- creating a table: CREATE TABLE, no past question.
- inserting data: INSERT INTO, no past question.
- altering tables: ALTER TABLE, no past question.
- queries: steps of querying and SELECT, INSERT, UPDATE, DELETE (Nov 2023, Jun 2025).
- deleting database: DROP DATABASE, no past question.
- deleting data and tables: DELETE and DROP TABLE, no past question.
- PHP myadmin and databasebugs: phpMyAdmin and bugs (Nov 2022, Nov 2023, Dec 2025), errors and exceptions (Jun 2025).