Alex Mcp
Alex Mcp

Reputation: 19315

Help troubleshooting PDO prepared statement

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!

Upvotes: 3

Views: 1171

Answers (1)

Joanne C
Joanne C

Reputation: 1115

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.

Upvotes: 6

Related Questions