1

I have a problem, when I want to connect my PHP code to my database, This error shows me in the picture But when I connect my database via the terminal this is working

https://i.stack.imgur.com/PoIW7.png

<?php

$host='localhost';
$db='canda';
$user='root';
$pass='123456789';

try{
    new PDO("mysql:host=".$host
                ."; dbname=".$db,
                $user, $pass);
}catch (PDOException $e) {
    echo $e;
}

PDOException: SQLSTATE[HY000] [2002] No such file or directory in /Users/mac/Desktop/test.php:11 Stack trace: #0 /Users/mac/Desktop/test.php(11): PDO->__construct('mysql:host=loca...', 'root', 'password') #1 {main}

Next
  • 47
  • 7
  • 2
    Possible duplicate of [PDOException: SQLSTATE\[HY000\] \[2002\] No such file or directory](https://stackoverflow.com/questions/29695450/pdoexception-sqlstatehy000-2002-no-such-file-or-directory) – aynber Feb 06 '19 at 20:06
  • 2
    Mysql drivers replace `localhost` with a supposed path to a local unix socket, which never seems to exist on Mac. use `127.0.0.1` instead so it actually uses the TCP stack. – Sammitch Feb 06 '19 at 20:07
  • when I change localhost with 127.0.0.1 I have this error message PDOException: PDO::__construct(): The server requested authentication method unknown to the client [caching_sha2_password] in /Users/mac/Desktop/test.php:11 Stack trace: #0 /Users/mac/Desktop/test.php(11): PDO->__construct('mysql:host=127....', 'root', 'FriZerX11') #1 {main} Next PDOException: SQLSTATE[HY000] [2054] The server requested authentication method unknown to the client in /Users/mac/Desktop/test.php:11 Stack trace: #0 /Users/mac/Desktop/test.php(11): PDO->__construct('mysql:host=127....', 'root', 'FriZerX11') #1 {main} – Next Feb 06 '19 at 20:21
  • 1
    @AflaYoussef careful about showing your credentials on a public forum. You probably need to create 'root'@'127.0.0.1' in your mysql user table that matches the PDO connexion string. You should find how to do this here no problem. Also : when posting any similar question (especially with Apple) , it is more useful to know the OS version, and the method you used to install the software causing you issues. – YvesLeBorg Feb 06 '19 at 20:51

1 Answers1

0

There you go for much cleaner version;

 $host      = DB_HOST; // just ignore constants //
 $user      = DB_USER;
 $pass      = DB_PASS;
 $dbname    = DB_NAME;

   $dsn = 'mysql:host=' . $host . ';dbname=' . $dbname;
    // Set options
    $options = array(
        PDO::ATTR_PERSISTENT    => true,
        PDO::ATTR_ERRMODE       => PDO::ERRMODE_EXCEPTION
    );
    // Create a new PDO instanace
    try{
         new PDO($dsn, $user, $pass, $options);
    }
    // Catch any errors
    catch(PDOException $e){
        echo $e;
    }

If this won't gonna work, then here you go pdoexception-sqlstatehy000-2002-no-such-file-or-directory

Ömer Atagün
  • 94
  • 1
  • 4