D
D
Daniil Sukhikh2020-05-02 11:51:00
PHP
Daniil Sukhikh, 2020-05-02 11:51:00

pdo php not working?

pdo query not working, returns false.

<?php
$host = 'localhost';
$user = 'root';
$password = 'root';
$db_name = 'db_des';
$options = [
  PDO::ATTR_ERRMODE => PDO::ERRMODE_SILENT,
  PDO::ATTR_EMULATE_PREPARES => true,
  PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
];

try {
  $connection = new PDO("mysql:host=$host; $dbname=$db_name", $user, $password, $options);
} catch (Exception $e) {
  echo 'Ошибка БД: ' . $e->getMessage();
}
$sth = $connection->query('SELECT * FROM `pages`');
var_dump($sth);
?>

Table
5ead3471301fa070748263.png

Answer the question

In order to leave comments, you need to log in

3 answer(s)
S
Sergey, 2020-05-02
@danchikraw

Set the ERRMODE error level to full and debug. Then there will be no questions.

F
FanatPHP, 2020-05-02
@FanatPHP

Where did you get this horror?
It looks like the code from my article, but someone mutilated it.
ERRMODE should be PDO::ERRMODE_EXCEPTION
in DSN no need to write gag. what is $dbname?!
try catch must be thrown out
var_dump($sth) will return not what you think it is
necessary to add charset, so that later you don’t run around again with the questions “oh, mine’s crazy”

<?php
$host = 'localhost';
$user = 'root';
$password = 'root';
$db_name = 'db_des';
$charset = 'utf8mb4';
$options = [
  PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
  PDO::ATTR_EMULATE_PREPARES => true,
  PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
];
$pdo = new PDO("mysql:host=$host;dbname=$db_name;charset=$charset", $user, $password, $options);

$sth = $pdo->query('SELECT * FROM `pages`');
var_dump($sth->fetchAll());

S
SORDELIUSE, 2020-05-02
@SORDELIUSE

$sth = $connection->query('SELECT * FROM `pages`');
return $sth;

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question