Troubleshoot prepared PDO statement

I just started learning aboud PDO and prepared statements (which seem to be memorable to me to use mysql_real_escape_string () every time), but I had problems with the script working correctly:

<?php
error_reporting(E_ALL);
echo "start";

try{
    $dbh=new PDO('mysql:host=localhost;dbname=DBNAME','USER','PWD');
} 
catch(PDOException $e){
    echo 'Error connecting to MySQL!: '.$e->getMessage();
    exit();
}

$dbh->prepare('SELECT * FROM users WHERE uid= ?');
$dbh->execute(array('15400743'));
$result=$dbh->fetchAll();
print_r($result);
echo "end";
?>

This is pretty much copied from the sample code, but only "start" is returned when executed. I double checked my db / user / pw. Anything else people see wrong? Thanks!

+3
source share
1 answer

The right way:

<?php
error_reporting(E_ALL);
echo "start";

try{
    $dbh=new PDO('mysql:host=localhost;dbname=DBNAME','USER','PWD');
} 
catch(PDOException $e){
    echo 'Error connecting to MySQL!: '.$e->getMessage();
    exit();
}

$stmt = $dbh->prepare('SELECT * FROM users WHERE uid= ?');
$stmt->execute(array('15400743'));
$result = $stmt->fetchAll();
print_r($result);
echo "end";
?>

Pay attention to the preparation for the $ stmt variable and its subsequent use.

+6
source

Source: https://habr.com/ru/post/1718861/


All Articles