Welcome to our comprehensive guide on connecting PHP with MySQL using the MySQLi extension! In this lesson, we'll walk you through the process step-by-step, explaining why things work the way they do, and providing practical examples for real-world projects.
MySQLi (MySQL Improved) is an interface for MySQL databases in PHP. It allows you to create a connection with a MySQL database, execute queries, and handle errors in a more efficient way compared to the traditional MySQL extension.
Let's dive into the practical part and learn how to connect to a MySQL database using PHP and MySQLi.
<?php
$servername = "localhost";
$username = "your_username";
$password = "your_password";
$dbname = "your_database";
// Create a new MySQLi object
$conn = new mysqli($servername, $username, $password, $dbname);
// Check the connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
?>π Note: Replace your_username, your_password, and your_database with your actual database credentials.
Now that we have established a connection, let's test it by querying the database for some data.
<?php
// Select database
$conn->select_db($dbname);
// Query the database
$sql = "SELECT id, username FROM users";
$result = $conn->query($sql);
// Display the results
if ($result->num_rows > 0) {
// Output data of each row
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"] . " - username: " . $row["username"] . "<br>";
}
} else {
echo "0 results";
}
?>π Note: This code assumes that you have a table named users in your database with columns id, username.
What is the purpose of the `mysqli` extension in PHP?
In this lesson, we learned how to connect PHP with MySQL using the MySQLi extension. We discussed why MySQLi is a better choice, and walked through the steps of establishing a connection and querying a database.
In the next lesson, we'll dive deeper into MySQLi and explore how to create, update, and delete records in a database using PHP. Stay tuned!