0

I need help with connection MySQL, I have a problem connecting to the database, what I am doing wrong ? Please send me an answer because I searched solution for about 2h and nothing.

This is a picture of the full error.

<?php
class Db {
   private $connection;

   public function __construct($servername, $dbname, $username, $password) {

       $this->connection = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
   }

   public function query($sql, $args = []) {
       if (!$args) {
           return $this->connection->query($sql);
       }

       $stmt = $this->connection->prepare($sql);
       $stmt->execute($args);
       return $stmt;
   }

   public function entryExists($table, $id) {
       $row = $this->query("SELECT * FROM $table WHERE id = $id")->fetch();

       if (!$row) {
           return false;;
       }
       else {
           return true;
       }
   }

   public function getRows($sql, $values = []) {
       $stmt = $this->query($sql, $values);
       return $stmt->fetchAll();
   }

   public function getFirstMatch($sql) {
       $stmt = $this->query($sql);
       return $stmt->fetch();
   }
}
?>

Jankos
  • 11
  • 2
    Please avoid posting [images](https://meta.stackoverflow.com/questions/285551/why-not-upload-images-of-code-errors-when-asking-a-question) of code or errors, it should be *text* in your question. – Stu Feb 13 '22 at 15:54
  • The error contains `mysql:host=;dbn…` as the beginning of the connection string. So `$servername` is empty. Check the code where you’re doing `new Db("some.host.name")` – rickdenhaan Feb 13 '22 at 16:06
  • 1
    Does this answer your question? [PDOException SQLSTATE\[HY000\] \[2002\] No such file or directory](https://stackoverflow.com/questions/20723803/pdoexception-sqlstatehy000-2002-no-such-file-or-directory) – Martin Zeitler Feb 13 '22 at 16:08

1 Answers1

0

I think or are you sending empty values in your constructor function? Maybe you should try entering the values that it should take by default :) I hope my answer will help you. Excuse my English.