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
wasir
Forum Commoner
Posts: 49 Joined: Sun Jul 08, 2007 11:28 pm
Post
by wasir » Sun Oct 24, 2010 9:08 pm
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?
Weirdan
Moderator
Posts: 5978 Joined: Mon Nov 03, 2003 6:13 pm
Location: Odessa, Ukraine
Post
by Weirdan » Sun Oct 24, 2010 10:08 pm
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
Post
by wasir » Mon Oct 25, 2010 12:23 am
Thanks Weirdan. Appreciate your help.