Skip to content
PHP Logo

How can PHP be used for Object-Oriented Programming (OOP) in conjunction with MySQL databases?

To use PHP for Object-Oriented Programming (OOP) in conjunction with MySQL databases, you can create classes to represent database tables and use methods within these classes to interact with the database. This allows for better organization of code, reusability, and easier maintenance when working with MySQL databases in PHP.

php
<?php
// Create a class to represent a user table in the database
class User {
    private $conn;

    public function __construct($conn) {
        $this->conn = $conn;
    }

    public function getUserById($id) {
        $query = "SELECT * FROM users WHERE id = :id";
        $stmt = $this->conn->prepare($query);
        $stmt->bindParam(':id', $id);
        $stmt->execute();
        return $stmt->fetch();
    }

    public function updateUser($id, $data) {
        $query = "UPDATE users SET name = :name, email = :email WHERE id = :id";
        $stmt = $this->conn->prepare($query);
        $stmt->bindParam(':id', $id);
        $stmt->bindParam(':name', $data['name']);
        $stmt->bindParam(':email', $data['email']);
        $stmt->execute();
    }
}

// Connect to MySQL database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);

// Create an instance of the User class
$user = new User($conn);

// Example of using the User class to get and update user data
$userData = $user->getUserById(1);
echo "User Name: " . $userData['name'];

$user->updateUser(1, ['name' => 'John Doe', 'email' => 'john.doe@example.com']);
?>