Current Affairs updated daily
KalviGavaniKalviGavani
Class 12 · Tamil Nadu State Board

Connecting PHP and MySQL Exercise Solutions | KalviGavani

Samacheer Kalvi Class 12 Computer Applications Chapter 9 Connecting PHP and MySQL exercise solutions — mysqli_connect, CRUD operations, result fetching, prepared statements, error handling with worked PHP/MySQL examples.

Updated 13 June 202613 min read

Chapter 9 — Connecting PHP and MySQL: Exercise Solutions Guide

How to Use This Page

1. Attempt every exercise on your own before reading the solutions. 2. Compare your method with the answer shown — focus on the logic, not just the final output. 3. Practise writing connection and query code by hand; the exam often asks complete programs.


Key Concepts (Quick Recap)

  • mysqli_connect($host, $user, $pass, $db) — establishes a connection to a MySQL database server.
  • mysqli_connect_error() — returns a description of the last connection error.
  • mysqli_query($conn, $sql) — executes a SQL query on the database.
  • mysqli_fetch_array($result) — fetches a result row as an associative array, numeric array, or both.
  • mysqli_fetch_assoc($result) — fetches a result row as an associative array (column names as keys).
  • mysqli_fetch_row($result) — fetches a result row as a numeric (indexed) array.
  • mysqli_num_rows($result) — returns the number of rows in a result set.
  • mysqli_close($conn) — closes the database connection.
  • CRUD — Create (INSERT), Read (SELECT), Update (UPDATE), Delete (DELETE).
  • Prepared statements use mysqli_prepare(), mysqli_stmt_bind_param(), and mysqli_stmt_execute() to prevent SQL injection.
  • Always check for connection and query errors before proceeding.

I. Choose the Best Answer (MCQs)

1. Which function is used to connect PHP to a MySQL database?
Answer

(a) mysql_connect()    (b) mysqli_connect()    (c) db_connect()    (d) pdo_connect()

Answer(b) mysqli_connect()

Explanation: mysqli_connect() is the improved MySQL function (the older mysql_connect() is deprecated and removed in PHP 7+). The "i" stands for "improved."


2. What does mysqli_query() return for a successful SELECT query?
Answer

(a) TRUE    (b) A result object    (c) Number of rows    (d) An array

Answer(b) A result object

Explanation: For SELECT/SHOW/DESCRIBE queries, mysqli_query() returns a mysqli_result object. For INSERT/UPDATE/DELETE, it returns TRUE on success.


3. Which function fetches a result row as an associative array?
Answer

(a) mysqli_fetch_row()    (b) mysqli_fetch_array()    (c) mysqli_fetch_assoc()    (d) mysqli_fetch_all()

Answer(c) mysqli_fetch_assoc()

Explanation: mysqli_fetch_assoc() returns a row with column names as keys (e.g., $row['name']). mysqli_fetch_row() uses numeric indices; mysqli_fetch_array() can return both.


4. What does mysqli_num_rows($result) return?
Answer

(a) Number of columns    (b) Number of affected rows    (c) Number of rows in the result set    (d) Number of tables

Answer(c) Number of rows in the result set

Explanation: It counts rows returned by a SELECT query. For INSERT/UPDATE/DELETE, use mysqli_affected_rows($conn) instead.


5. Which SQL statement is used to insert new data into a table?
Answer

(a) SELECT    (b) UPDATE    (c) INSERT    (d) DELETE

Answer(c) INSERT

Explanation: INSERT adds new rows. Syntax: INSERT INTO table (col1, col2) VALUES ('val1', 'val2').


6. What is the purpose of mysqli_close()?
Answer

(a) Closes the result set    (b) Closes the database connection    (c) Closes the browser    (d) Closes the PHP script

Answer(b) Closes the database connection

Explanation: mysqli_close($conn) frees the connection resource. It's good practice to close connections when done.


7. Which function returns the number of rows affected by an INSERT, UPDATE, or DELETE query?
Answer

(a) mysqli_num_rows()    (b) mysqli_affected_rows()    (c) mysqli_row_count()    (d) mysqli_insert_id()

Answer(b) mysqli_affected_rows()

Explanation: mysqli_affected_rows($conn) returns the number of rows changed by the last INSERT, UPDATE, or DELETE. mysqli_num_rows() is for SELECT results only.


8. In a prepared statement, what does mysqli_stmt_bind_param($stmt, "ss", $name, $email) mean?
Answer

(a) Binds two integer values    (b) Binds two string values    (c) Binds one string and one integer    (d) Binds a result set

Answer(b) Binds two string values

Explanation: The type string "ss" means both parameters are strings. Common type characters: s = string, i = integer, d = double, b = blob.


9. What happens if mysqli_connect() fails?
Answer

(a) Returns 0    (b) Returns NULL    (c) Returns FALSE    (d) Throws an exception

Answer(c) Returns FALSE

Explanation: On failure, mysqli_connect() returns FALSE. Use mysqli_connect_error() to get the error message.


10. Which SQL keyword is used to modify existing data in a table?
Answer

(a) INSERT    (b) ALTER    (c) UPDATE    (d) MODIFY

Answer(c) UPDATE

Explanation: UPDATE table SET col='new' WHERE condition modifies existing rows. ALTER changes table structure, not data.


II. Fill in the Blanks

1. The function mysqli_connect() is used to establish a connection between PHP and MySQL.

2. mysqli_query() executes a SQL query on the database.

3. mysqli_fetch_assoc() fetches a result row as an associative array with column names as keys.

4. mysqli_num_rows() returns the number of rows in a SELECT result set.

5. mysqli_affected_rows() returns the number of rows changed by INSERT, UPDATE, or DELETE.

6. mysqli_close() closes the database connection.

7. The four CRUD operations stand for Create, Read, Update, and Delete.

8. In prepared statements, mysqli_prepare() creates a prepared statement from a SQL template.

9. The type specifier "i" represents an integer in mysqli_stmt_bind_param().

10. mysqli_connect_error() returns the error description when a connection fails.


III. True or False

1. mysql_connect() is the recommended function to connect PHP to MySQL. — False. mysql_connect() is deprecated and removed in PHP 7+. Use mysqli_connect() or PDO.

2. mysqli_query() returns TRUE for successful INSERT, UPDATE, and DELETE queries. — True. For non-SELECT queries, it returns TRUE on success; for SELECT, it returns a result object.

3. mysqli_fetch_assoc() returns both numeric and associative arrays. — False. It returns only an associative array. Use mysqli_fetch_array() for both.

4. You must always close a database connection with mysqli_close(). — True. It's good practice to close connections, though PHP auto-closes them when the script ends.

5. Prepared statements help prevent SQL injection attacks. — True. They separate SQL logic from data, so user input cannot alter the query structure.

6. mysqli_num_rows() can be used after an INSERT query to get the number of inserted rows. — False. mysqli_num_rows() works only with SELECT results. Use mysqli_affected_rows() for INSERT/UPDATE/DELETE.

7. The WHERE clause is optional in an UPDATE statement. — True. But without it, ALL rows will be updated, which is usually unintended.

8. mysqli_fetch_row() returns an associative array. — False. It returns a numeric (indexed) array. Use mysqli_fetch_assoc() for associative.

9. The die() function stops the script and displays an error message. — True. It is often used with mysqli_connect() or mysqli_query() for error handling.

10. A SELECT query with no matching rows returns FALSE. — False. It returns a result object with zero rows. Use mysqli_num_rows() to check if rows exist.


IV. Match the Following

Set A

No.Column ANo.Column B
1mysqli_connect()dConnect to MySQL server
2mysqli_query()eExecute SQL query
3mysqli_fetch_assoc()aFetch row as associative array
4mysqli_num_rows()cCount rows in result
5mysqli_close()bClose connection

Set B

No.Column ANo.Column B
1INSERTdAdd new data
2SELECTeRetrieve data
3UPDATEaModify existing data
4DELETEcRemove data
5WHEREbFilter condition

V. Short Answer Questions

1. Write the PHP code to connect to a MySQL database named "school" on localhost.
<?php
$host = "localhost";
$user = "root";
$pass = "";
$db   = "school";

$conn = mysqli_connect($host, $user, $pass, $db);

if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully!";
?>

2. What is the difference between mysqli_fetch_assoc(), mysqli_fetch_row(), and mysqli_fetch_array()?
Answer
FunctionReturn TypeExample Access
mysqli_fetch_assoc()Associative array$row['name']
mysqli_fetch_row()Numeric array$row[0]
mysqli_fetch_array()Both (default)$row['name'] or $row[0]

mysqli_fetch_array() can take an optional second parameter: MYSQLI_ASSOC, MYSQLI_NUM, or MYSQLI_BOTH (default).


3. How do you retrieve and display all records from a MySQL table using PHP?
<?php
$conn = mysqli_connect("localhost", "root", "", "school");
$sql = "SELECT * FROM student";
$result = mysqli_query($conn, $sql);

while ($row = mysqli_fetch_assoc($result)) {
    echo "Roll: " . $row["rollno"] . " - Name: " . $row["name"] . "<br>";
}
mysqli_close($conn);
?>
Answer

The while loop fetches one row at a time until no more rows remain.


4. Write an SQL INSERT statement and execute it using PHP.
<?php
$conn = mysqli_connect("localhost", "root", "", "school");

$name = "Kumar";
$age  = 17;
$mark = 450;

$sql = "INSERT INTO student (name, age, total_mark) VALUES ('$name', $age, $mark)";

if (mysqli_query($conn, $sql)) {
    echo "Record inserted successfully!";
} else {
    echo "Error: " . mysqli_error($conn);
}
mysqli_close($conn);
?>

5. What are prepared statements? Why are they important?
Answer

Prepared statements are a feature of MySQL that separates SQL query structure from data values. They are created using mysqli_prepare().

Why important:

  • Prevents SQL injection — user input is never directly concatenated into SQL.
  • Improves performance — the query is parsed once and can be executed multiple times.
  • Cleaner code — separates logic from data.

Example:

<?php
$conn = mysqli_connect("localhost", "root", "", "school");
$stmt = mysqli_prepare($conn, "INSERT INTO student (name, age) VALUES (?, ?)");
mysqli_stmt_bind_param($stmt, "si", $name, $age);

$name = "Priya";
$age  = 16;
mysqli_stmt_execute($stmt);

$name = "Ravi";
$age  = 17;
mysqli_stmt_execute($stmt);

mysqli_stmt_close($stmt);
mysqli_close($conn);
?>

6. Write a DELETE query in PHP with a WHERE clause.
<?php
$conn = mysqli_connect("localhost", "root", "", "school");

$rollno = 105;
$sql = "DELETE FROM student WHERE rollno = $rollno";

if (mysqli_query($conn, $sql)) {
    echo "Record deleted successfully!";
} else {
    echo "Error: " . mysqli_error($conn);
}
mysqli_close($conn);
?>
Answer

Important: Always use a WHERE clause with DELETE; otherwise, all rows will be deleted.


VI. Detailed Answer Questions

1. Write a complete PHP program to perform all CRUD operations on a "student" table.
<?php
// Connection
$conn = mysqli_connect("localhost", "root", "", "school");
if (!$conn) die("Connection failed: " . mysqli_connect_error());

// CREATE (Insert)
$sql = "INSERT INTO student (name, age, mark) VALUES ('Arun', 16, 480)";
mysqli_query($conn, $sql);
echo "Record inserted.<br>";

// READ (Select)
$sql = "SELECT * FROM student";
$result = mysqli_query($conn, $sql);
while ($row = mysqli_fetch_assoc($result)) {
    echo "Roll: {$row['rollno']} | Name: {$row['name']} | Age: {$row['age']} | Mark: {$row['mark']}<br>";
}

// UPDATE
$sql = "UPDATE student SET mark = 500 WHERE name = 'Arun'";
mysqli_query($conn, $sql);
echo "Record updated.<br>";

// DELETE
$sql = "DELETE FROM student WHERE rollno = 3";
mysqli_query($conn, $sql);
echo "Record deleted.<br>";

mysqli_close($conn);
?>
Answer

This program demonstrates all four CRUD operations in sequence. In practice, each operation would typically be in a separate script or triggered by different form submissions.


2. Explain the steps to connect PHP with MySQL with error handling.
Answer

Step 1 — Create the connection:

$conn = mysqli_connect("localhost", "root", "", "school");

Parameters: host, username, password, database name.

Step 2 — Check connection:

if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully!<br>";

mysqli_connect_error() gives the specific error message.

Step 3 — Execute queries:

$sql = "SELECT * FROM student";
$result = mysqli_query($conn, $sql);

if (!$result) {
    die("Query failed: " . mysqli_error($conn));
}

Always check if the query executed successfully.

Step 4 — Fetch and process results:

while ($row = mysqli_fetch_assoc($result)) {
    echo $row['name'] . "<br>";
}

Step 5 — Close the connection:

mysqli_close($conn);

Best practices: always check for errors, always close connections, and use prepared statements for user input.


3. Write a PHP program to create an HTML form that inserts student data into a MySQL database.
Answer

HTML Form (insert.html):

<!DOCTYPE html>
<html>
<body>
<h2>Student Registration</h2>
<form action="insert.php" method="POST">
    <label>Name:</label>
    <input type="text" name="name" required><br>
    <label>Age:</label>
    <input type="number" name="age" required><br>
    <label>Total Marks:</label>
    <input type="number" name="mark" required><br>
    <input type="submit" value="Register">
</form>
</body>
</html>

PHP Processing (insert.php):

<?php
$conn = mysqli_connect("localhost", "root", "", "school");
if (!$conn) die("Connection failed: " . mysqli_connect_error());

$name = mysqli_real_escape_string($conn, $_POST['name']);
$age  = intval($_POST['age']);
$mark = intval($_POST['mark']);

$sql = "INSERT INTO student (name, age, mark) VALUES ('$name', $age, $mark)";

if (mysqli_query($conn, $sql)) {
    echo "Student registered successfully!";
    echo "<br><a href='insert.html'>Add another</a>";
} else {
    echo "Error: " . mysqli_error($conn);
}
mysqli_close($conn);
?>

Key security measures: mysqli_real_escape_string() prevents SQL injection, intval() ensures numeric types.


4. Explain prepared statements with a complete example.
Answer

Prepared statements separate the SQL structure from data values using placeholders (?). This prevents SQL injection because the data is never interpreted as SQL code.

<?php
$conn = mysqli_connect("localhost", "root", "", "school");
if (!$conn) die("Connection failed: " . mysqli_connect_error());

// Step 1: Prepare the statement with placeholders
$stmt = mysqli_prepare($conn, "INSERT INTO student (name, age, mark) VALUES (?, ?, ?)");

if (!$stmt) {
    die("Prepare failed: " . mysqli_error($conn));
}

// Step 2: Bind parameters (s=string, i=integer, i=integer)
mysqli_stmt_bind_param($stmt, "sii", $name, $age, $mark);

// Step 3: Set values and execute
$name = "Divya";
$age  = 16;
$mark = 490;
mysqli_stmt_execute($stmt);

// Execute again with different values
$name = "Karthik";
$age  = 17;
$mark = 475;
mysqli_stmt_execute($stmt);

echo "Records inserted successfully!";

// Close statement and connection
mysqli_stmt_close($stmt);
mysqli_close($conn);
?>

Advantages of prepared statements: 1. Security — SQL injection is impossible because parameters are sent separately. 2. Performance — The query is compiled once; subsequent executions reuse the compiled form. 3. Reusability — The same statement can be executed multiple times with different values.

Type specifiers in mysqli_stmt_bind_param():

  • s — string
  • i — integer
  • d — double (float)
  • b — blob (binary data)

Common Mistakes

1. Using mysql_connect() instead of mysqli_connect() — the old mysql_ functions are deprecated and removed in PHP 7+. Always use mysqli_.

2. Not checking for connection errors — always test the connection with if (!$conn) before proceeding.

3. Concatenating user input directly into SQL queries — this is vulnerable to SQL injection. Use prepared statements or mysqli_real_escape_string().

4. Confusing mysqli_num_rows() and mysqli_affected_rows() — mysqli_num_rows() is for SELECT results; mysqli_affected_rows() is for INSERT/UPDATE/DELETE.

5. Forgetting the WHERE clause in UPDATE or DELETE — without WHERE, all rows in the table will be modified or deleted.

6. Not closing connections and result sets — always call mysqli_close() and mysqli_free_result() to free resources.

7. Using mysqli_fetch_assoc() on a non-SELECT result — this only works on SELECT/SHOW results, not on TRUE returned by INSERT/UPDATE/DELETE.


Exam Checklist

  • [ ] Can write the connection code with error handling (mysqli_connect + die)
  • [ ] Know the difference between mysqli_fetch_assoc, mysqli_fetch_row, and mysqli_fetch_array
  • [ ] Can write CRUD operations (INSERT, SELECT, UPDATE, DELETE) in PHP
  • [ ] Can create an HTML form that submits data to a PHP script for database insertion
  • [ ] Understand prepared statements and can write mysqli_prepare/bind/execute code
  • [ ] Know type specifiers (s, i, d, b) for mysqli_stmt_bind_param()
  • [ ] Can use mysqli_real_escape_string() for input sanitization
  • [ ] Understand when to use mysqli_num_rows() vs mysqli_affected_rows()
  • [ ] Can display database records in an HTML table using a while loop
  • [ ] Know the complete flow: connect → query → fetch → display → close

Frequently Asked Questions

Use mysqli_connect($host, $user, $password, $dbname) to establish a connection, then check for errors with mysqli_connect_error().
← Browse all Class 12 Exercise Solutions

More exercise solutions