← Back to Chapters

PHP MySQLi Object Oriented

? PHP MySQLi Object Oriented

? Overview

MySQLi in PHP supports an object-oriented approach, which allows you to interact with MySQL databases using objects and methods rather than procedural functions. This style improves readability and code organization.

? Creating a Connection

? View Code Example
// Create a MySQLi object-oriented connection
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

$conn = new mysqli($servername, $username, $password, $dbname);

if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";

? Executing Queries

? View Code Example
// Execute a SELECT query using query()
$sql = "SELECT id, first_name, last_name FROM users";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
echo "id: ".$row["id"]." - Name: ".$row["first_name"]." ".$row["last_name"]."<br>";
}
} else {
echo "0 results";
}

? Updating Data

? View Code Example
// Update records using object-oriented MySQLi
$sql = "UPDATE users SET email='john.doe@newdomain.com' WHERE id=1";
if ($conn->query($sql) === TRUE) {
echo "Record updated successfully. Affected rows: ".$conn->affected_rows;
} else {
echo "Error updating record: ".$conn->error;
}

❌ Deleting Data

? View Code Example
// Delete a record using DELETE query
$sql = "DELETE FROM users WHERE id=2";
if ($conn->query($sql) === TRUE) {
echo "Record deleted successfully. Affected rows: ".$conn->affected_rows;
} else {
echo "Error deleting record: ".$conn->error;
}

? Closing the Connection

? View Code Example
// Close the database connection
$conn->close();
echo "Connection closed successfully";

✅ Tips & Best Practices

  • Always check $conn->connect_error after creating the connection.
  • Use prepared statements to prevent SQL injection.
  • Stay consistent with object-oriented syntax.

? Try It Yourself

  • Create a script that inserts multiple users using object-oriented MySQLi.
  • Fetch records using fetch_object().
  • Combine SELECT, UPDATE, and DELETE operations in one script.