I am trying to learn mySQL PDO .. read tutorial after tutorial and trying to apply different ways to perform a simple SELECT statement.
Here is my latest attempt:
<?
include("inc/connPDO.php"); // hostname, username and password and dbName are in here
try {
$dbh = new PDO("mysql:host=$hostname;dbname=$dbName", $username, $password);
/*** echo a message saying we have connected ***/
echo 'Connected to database'; // this outputs appropriately
/*** The SQL SELECT statement ***/
$sql = "SELECT * FROM rofWeapons";
echo '<p>'.$sql;
foreach ($dbh->query($sql) as $row){ // *** line 11 error
print $row['weaponName'] .' - '. $row['weaponType'] . '<br />';
}
/*** close the database connection ***/
$dbh = null;
}
catch(PDOException $e)
{
echo $e->getMessage();
}
?>
The output is the following:
Connected to database
SELECT * FROM rofWeapons
Warning: Invalid argument supplied for foreach() in /home/path/to/script/script.php on line 11
I am following a tutorial.. the foreach looks good. Why is it an invalid argument?
When I enter "SELECT * FROM rofWeapons" into mySQL queries the table perfectly fine.
A little help please?
Another Attempt
If I try a PREPARE statement:
/*** The SQL SELECT statement ***/
$weaponType=1;
$sql = "SELECT * FROM rofWeapons WHERE weaponType=:weaponType";
$stmt = $dbh->prepare($sql); // *** error Line 12 ***
$stmt->bindValue(':weaponType', $weaponType, PDO::PARAM_INT);
$stmt->execute();
$stmt->setFetchMode(PDO::FETCH_ASSOC);
while($row = $stmt->fetch()) {
print $row['weaponName'] .' - '. $row['weaponType'] . '<br />';
}
I get no error. Nothing at all.
This is very frustrating. What am I doing wrong?
You have not fetched the array for using in the loop.
Change:
foreach ($dbh->query($sql) as $row){
//YOUR CODE STUFF
}
To:
foreach ($dbh->query($sql)->fetchAll as $row){
//YOUR CODE STUFF
}
It works fine.
Im not sure if this would fix your problem but you may want to try this:
$sql = "SELECT * FROM rofWeapons";
$sth = $dbh->query($sql);
while($row = $sth->fetch(PDO::FETCH_ASSOC))
{
print $row['weaponName'] .' - '. $row['weaponType'] . '<br />';
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.