Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't connect to MySQL with PDO

Tags:

php

mysql

pdo

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 not connect." when I'm trying to make the connection. When I used PHPStorms inside Database program, I had to change my serverTimezone to Europe/Amsterdam and then I was able to connect to my db.

I tried to add the port number in the 'new PDO()' code. I tried to change the timezone in the code and on my MySQL server but it gives this error;

mysql> SET GLOBAL time_zone = 'Europe/Amsterdam';
ERROR 1298 (HY000): Unknown or incorrect time zone: 'Europe/Amsterdam'
<?php

try {
    $pdo = new PDO('mysql:host=localhost:dbname=mytodo', 'root', '');
} catch (PDOException $e) {
    die('Could not connect.');
}

$statement = $pdo->prepare('select * from todos');

$statement->execute();

var_dump($statement->fetchAll());

require 'index.view.php';

Extra information:

mysql> SELECT @@global.time_zone, @@session.time_zone;
+--------------------+---------------------+
| @@global.time_zone | @@session.time_zone |
+--------------------+---------------------+
| SYSTEM             | SYSTEM              |
+--------------------+---------------------+

1 Answers

The tutorial you are following is very outdated.

A code connecting to PDO has to follow certain rules explained in my article How to connect to MySQL with PDO. In brief

  • it should configure error reporting mode
  • it should set the connection charset, the right way
  • it shouldn't catch it's own errors to report them
  • it should follow correct DSN syntax, without any extra decorations
  • it also coud set a couple useful settings

So the code should be like this

$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";
$pdo = new \PDO($dsn, $user, $pass, $options);

Here you can see the proper connection code that does a lot of things. Among them, it tells you what the actual problem is when your code cannot connect to database.

like image 193
Your Common Sense Avatar answered Oct 31 '25 11:10

Your Common Sense



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!