PDO -> Execute

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
wasir
Forum Commoner
Posts: 49
Joined: Sun Jul 08, 2007 11:28 pm

PDO -> Execute

Post by wasir »

I've got a PHP PDO script that works fine with value in the query but doesn't work with question mark (?)

This one doesn't work.
Error - Warning: Invalid argument supplied for foreach() in <filename> on line <line number pointing on foreach...>

Code: Select all

$sql = 'SELECT id,firstName,lastName FROM tableName WHERE id=?';
$pds = $pdo->prepare($sql);
$pds->execute(array($_SESSION['ftlogin']));
foreach ($pdo->query($sql) as $row) {
	$name = $row['firstName'].' '.$row['lastName'];
}
But this one works fine

Code: Select all

$sql = 'SELECT id,firstName,lastName FROM tableName WHERE id="'.$_SESSION['ftlogin'].'"';
$pds = $pdo->prepare($sql);
$pds->execute();
foreach ($pdo->query($sql) as $row) {
	$name = $row['firstName'].' '.$row['lastName'];
}
What am I doing wrong?
User avatar
Weirdan
Moderator
Posts: 5978
Joined: Mon Nov 03, 2003 6:13 pm
Location: Odessa, Ukraine

Re: PDO -> Execute

Post by Weirdan »

The problem is that you're issuing another query instead of fetching data from executed statement. PDO::query() performs a query on its own. The following should work:

Code: Select all

$sql = 'SELECT id,firstName,lastName FROM tableName WHERE id=?';
$pds = $pdo->prepare($sql);
$pds->execute(array($_SESSION['ftlogin']));
$pds->setFetchMode(PDO::FETCH_ASSOC);
foreach ($pds as $row) {
        $name = $row['firstName'].' '.$row['lastName'];
}
wasir
Forum Commoner
Posts: 49
Joined: Sun Jul 08, 2007 11:28 pm

Re: PDO -> Execute

Post by wasir »

Thanks Weirdan. Appreciate your help.
Post Reply