DEV Community

Ghulam Mujtaba
Ghulam Mujtaba

Posted on

How to extract a database class?

To extract a database class in PHP, you can follow these steps:

Identify the database connection code:

First of all you have to find the part of your PHP code that connects to the database using PDO.

Extract the database connection logic:

Separate the database connection logic into a separate file or class.

Create a database class:

Create a new class that encapsulates the database connection logic.

Add database methods:

Add methods to the class for performing common database operations like selecting, inserting, updating, and deleting data.

Use the database class:

Create the database class and use its methods to interact with the database.

Here's an example of how you can extract a database class using PDO:

// database.php

class Database {
  public $con;

  public function __construct($dsn, $username, $password) {
    $this->con = new PDO($dsn, $username, $password);
  }

  public function select($query) {
    $stmt = $this->con->prepare($query);
    $stmt->execute();
    return $stmt->fetchAll();
  }

  public function insert($query) {
    $stmt = $this->conn->prepare($query);
    $stmt->execute();
    return $this->conn->lastInsertId();
  }
}
Enter fullscreen mode Exit fullscreen mode

Then, you can use the database class in your main code like this:

// main.php

require 'database.php';

$db = new Database('mysql:host=localhost;dbname=myapp', 'username', 'password');

$result = $db->select('SELECT * FROM applicants');
Enter fullscreen mode Exit fullscreen mode

By extracting the database class, you can keep your database logic organized and reusable, making it easier to maintain.

Top comments (0)

Some comments may only be visible to logged-in visitors. Sign in to view all comments.