Can't connect to MySQL with PDO

后端 未结 2 854
失恋的感觉
失恋的感觉 2021-01-16 06:23

I\'m following this tutorial, I\'m currently around minute 04:00 and I want to make a connection with my MySQL database through PDO. But my webpage will always give \"Could

相关标签:
2条回答
  • 2021-01-16 07:05

    The tutorial you are using is a bit outdated. And the essential part is

    die('Could not connect.');
    

    It's a nasty statement that, sadly, is wandering from one outdated tutorial to another. I even had to write a dedicated answer on Stack Overflow explaining why it is bad. The thing is, PDO already has an answer why you couldn't connect. But this code effectively muting it out.

    So the question is, how to properly connect with PDO, the way it will tell you what is certainly going wrong when something going wrong? And here goes my own tutorial entirely dedicated to the question How to connect to MySQL with PDO.

    $host = '127.0.0.1';
    $db   = 'mytodo';
    $user = 'root';
    $pass = '';
    $charset = 'utf8mb4';
    
    $options = [
        \PDO::ATTR_ERRMODE            => \PDO::ERRMODE_EXCEPTION,
        \PDO::ATTR_DEFAULT_FETCH_MODE => \PDO::FETCH_ASSOC,
        \PDO::ATTR_EMULATE_PREPARES   => false,
    ];
    $dsn = "mysql:host=$host;dbname=$db;charset=$charset";
    try {
         $pdo = new \PDO($dsn, $user, $pass, $options);
    } catch (\PDOException $e) {
         throw new \PDOException($e->getMessage(), (int)$e->getCode());
    }
    

    Here you can see the proper connection code that does a lot of things that are just missed in your tutorial. Among them, it tells you what the actual problem is.

    So you have to change your code and run it again. Then it will display you the actual error message. Then you will have to either read and fix it right away or, Google for the message you get and find a solution here on Stack Overflow.

    0 讨论(0)
  • 2021-01-16 07:08

    You have error in code near localhost

    Use semicolon in place of colon

    Write this instead:

    $pdo=new PDO('mysql:host=localhost;dbname=mytodo','root','');
    
    0 讨论(0)
提交回复
热议问题