Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Help troubleshooting PDO prepared statement

Tags:

php

pdo

I've just started learning aboud PDO and prepared statements (which sure seem to beat remembering to use mysql_real_escape_string() every time) but I'm having trouble getting the script to execute properly:

<?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 example code, but when executed only returns "start". I've double-checked my db/user/pw. Anything else people see wrong? Thanks!

like image 327
Alex Mcp Avatar asked Feb 04 '26 13:02

Alex Mcp


1 Answers

The correct way is:

<?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";
?>

Note the assinment of the prepare to the $stmt variable and the use of that afterwards.

like image 82
Joanne C Avatar answered Feb 07 '26 03:02

Joanne C



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!