Connecting PHP with MySQL (MySQLi)
Learn how to connect a PHP script to a MySQL database using the mysqli extension, run queries, and fetch results.
Introduction
You now know what MySQL is and how to write basic SQL commands. But those commands are only useful to a PHP application once PHP can actually talk to the database. That is exactly what the mysqli extension does.
In this lesson you will connect a PHP script to a MySQL database, run a query, and pull the results back into PHP variables you can loop over and display.
- What the mysqli extension is and where it comes from.
- The difference between its procedural and object-oriented styles.
- How to connect to MySQL with mysqli_connect() or new mysqli(...).
- How to check whether the connection succeeded.
- How to run a query and fetch its results.
- How to properly close a database connection.
What is MySQLi?
MySQLi ("MySQL Improved") is a PHP extension built specifically for communicating with MySQL databases. It replaced the older, now-removed `mysql_*` functions and added support for prepared statements, transactions, and an object-oriented interface, among other improvements.
MySQLi is enabled by default in most PHP installations, including XAMPP, so you generally do not need to install anything extra to use it.
Built for MySQL
MySQLi is designed specifically to work with MySQL and MySQL-compatible databases like MariaDB.
Two Styles
You can call it using plain functions (procedural) or through a mysqli object (object-oriented).
Prepared Statements
MySQLi supports prepared statements, which you will use to guard against SQL injection in a later lesson.
Enabled by Default
Ships enabled in most PHP setups, including XAMPP, with no extra installation required.
Procedural vs Object-Oriented Style
MySQLi offers two equivalent ways of doing the exact same work. The procedural style calls global functions like `mysqli_connect()` and passes the connection around as an argument. The object-oriented style creates a `mysqli` object with `new mysqli(...)` and calls methods directly on it.
Procedural Style
- mysqli_connect(...)
- mysqli_query($conn, $sql)
- mysqli_fetch_assoc($result)
- mysqli_close($conn)
Object-Oriented Style
- new mysqli(...)
- $conn->query($sql)
- $result->fetch_assoc()
- $conn->close()
Both styles are fully supported and equally valid. This lesson shows both, but most modern PHP codebases lean toward the object-oriented style since it reads more naturally and pairs well with other OOP code.
Connecting to MySQL
To connect, you need four pieces of information: the database host (usually "localhost" for local development), a username, a password, and the name of the database you want to use.
<?php
$host = "localhost";
$user = "root";
$password = "";
$database = "school";
$conn = mysqli_connect($host, $user, $password, $database);
?>The object-oriented equivalent creates a new `mysqli` instance with the same four arguments.
<?php
$host = "localhost";
$user = "root";
$password = "";
$database = "school";
$conn = new mysqli($host, $user, $password, $database);
?>By default, XAMPP's MySQL runs on "localhost" with username "root" and an empty password. Never use these defaults on a real, publicly accessible server.
Checking for Connection Errors
Connections can fail — the wrong password, MySQL not running, or a typo in the database name. Always check whether the connection succeeded before running any queries against it.
<?php
$conn = new mysqli("localhost", "root", "", "school");
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully!";
?>Connected successfully!The procedural equivalent uses `mysqli_connect_error()` after checking whether `mysqli_connect()` returned false.
<?php
$conn = mysqli_connect("localhost", "root", "", "school");
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
?>Running a Query
Once connected, you send SQL statements to the database with `mysqli_query()` (or the `->query()` method). It returns a result set for SELECT queries, or a simple true/false for INSERT, UPDATE, and DELETE.
<?php
$conn = new mysqli("localhost", "root", "", "school");
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, name, course FROM students";
$result = $conn->query($sql);
?>- For SELECT: a mysqli_result object you can loop over to read rows.
- For INSERT, UPDATE, DELETE: true on success, false on failure.
- On a serious error, query() can also return false — always check it before using $result.
Fetching Results
`fetch_assoc()` pulls one row at a time from the result set as an associative array, keyed by column name. Looping while `fetch_assoc()` returns a row is the most common pattern for displaying query results.
<?php
while ($row = $result->fetch_assoc()) {
echo $row["name"] . " - " . $row["course"] . "\n";
}
?>Amit Verma - PHP Development
Sara Khan - Web Design
Rahul Singh - Database SystemsIf you would rather have every row at once instead of looping manually, `fetch_all(MYSQLI_ASSOC)` returns the entire result set as an array of associative arrays.
<?php
$students = $result->fetch_all(MYSQLI_ASSOC);
foreach ($students as $student) {
echo $student["name"] . "\n";
}
?>Amit Verma
Sara Khan
Rahul SinghClosing the Connection
Once you are done with the database, close the connection to free up its resources. PHP does this automatically when a script ends, but it is good practice to close it explicitly, especially in longer-running scripts.
<?php
$conn->close();
// Procedural equivalent: mysqli_close($conn);
?>Common Mistakes
- Running a query before checking whether the connection actually succeeded.
- Forgetting that query() can return false and using $result without checking it.
- Mixing procedural and object-oriented mysqli calls in the same script inconsistently.
- Hardcoding real production database credentials directly in a committed PHP file.
Best Practices
- Always check $conn->connect_error (or mysqli_connect_error()) right after connecting.
- Pick one style — procedural or object-oriented — and stay consistent within a project.
- Close connections explicitly with close() once you are finished with them.
- Keep database credentials out of version control; load them from a separate config file.
Frequently Asked Questions
Is MySQLi the only way to connect PHP to MySQL?
No. PDO, covered in an upcoming lesson, is another built-in option that works with MySQL and several other database systems using one consistent API.
What happened to the old mysql_connect() functions?
The original mysql_* extension was deprecated and later fully removed from PHP. mysqli and PDO are its supported replacements.
Which is better: procedural or object-oriented MySQLi?
Neither is objectively better — they do the same work. Object-oriented style is generally preferred in modern codebases for readability and consistency with other OOP code.
Do I need to close the connection manually?
Not strictly, since PHP closes it automatically at the end of a script, but explicitly closing it is considered good practice, especially for long-running or resource-heavy scripts.
Is it safe to insert user input directly into a query like this?
No — the examples here use fixed queries for clarity. Never insert raw user input into a query string directly; the CRUD and Prepared Statements lessons cover this in detail.
Key Takeaways
- MySQLi is a PHP extension for communicating with MySQL, available in procedural and object-oriented styles.
- Connect with mysqli_connect() or new mysqli(host, user, password, database).
- Always check connect_error (or mysqli_connect_error()) before running queries.
- query() runs SQL; fetch_assoc() or fetch_all() pull rows back as PHP arrays.
- Close the connection with close() once you are done.
Summary
The mysqli extension is the bridge between your PHP code and a MySQL database: connect, check for errors, run a query, fetch the results, and close the connection.
In this lesson, you learned how to open a MySQLi connection, verify it succeeded, run a query, and read back the rows it returned. Next, you will put these building blocks to work performing full CRUD operations against a real table.
- You can connect to MySQL using mysqli_connect() or new mysqli(...).
- You know how to check for and handle connection errors.
- You can run a query and fetch its results with fetch_assoc() or fetch_all().
- You are ready to perform full CRUD operations.