This is my code:

class Database {

    private $host = 'localhost';
    private $db_name = 'myblog';
    private $username = 'root';
    private $password = '';
    private $conn;

public function connect() {
    $this->conn = null;

    try {
        $this->conn = new PDO('mysql:host=' . $this->host . '.dbname=' . $this->db_name,
         $this->username, $this->password);
        $this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    } catch(PDOException $e) {
        echo 'Connection Error:' .$e->getMessage();
    return $this->conn;

And this what did they say

Connection Error:SQLSTATE[HY000] [2002] php_network_getaddresses: getaddrinfo for localhost.dbname=myblog failed: No such host is known. <br />
<b>Fatal error</b>:  Uncaught Error: Call to a member function prepare() on null in C:\Users\agadir\Downloads\xampp3\htdocs\API project\Models\post.php:38
Stack trace:
#0 C:\Users\agadir\Downloads\xampp3\htdocs\API project\API\POST\read.php(18): Post-&gt;read()
#1 {main}
  thrown in <b>C:\Users\agadir\Downloads\xampp3\htdocs\API project\Models\post.php</b> on line <b>38</b><br />

1 Answer 1


Try this way:

CRUD operation with PDO Database Connection

My suggestion:

you can establish a database connection using PDO by creating a new instance of the Magento\Framework\DB\Adapter\AdapterInterface interface.

Here's an example of how to establish a database connection using PDO in Magento 2:

use Magento\Framework\App\ResourceConnection;

// Inject the ResourceConnection object into your class constructor
public function __construct(ResourceConnection $resourceConnection)
    $this->connection = $resourceConnection->getConnection();

// Use the getConnection() method to get the PDO object
public function getConnection()
    return $this->connection;

// Example query using PDO
public function executeQuery()
    $sql = "SELECT * FROM my_table";
    $stmt = $this->getConnection()->prepare($sql);
    $result = $stmt->fetchAll();
    return $result;

In this example, the ResourceConnection object is injected into the constructor of your class. This object provides access to the database connection via the getConnection() method.

You can then use the getConnection() method to retrieve the PDO object, which can be used to execute SQL queries.

Note that Magento 2 also provides a query builder interface (Magento\Framework\DB\Adapter\AdapterInterface) that can be used to build SQL queries in a more structured way. However, using PDO directly may be necessary in certain situations where more fine-grained control over the SQL query is required.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.