Reputation: 11
I have this code that works for my friend but when I run it, it gave this Warning: Invalid argument supplied for foreach() in C:\wamp64\www\DVD_show.php on line 10
What is the problem?
'''
<?php
try {
/*** connect to SQLite database ***/
$dbh = new PDO("sqlite:dvd.db");
//echo("ok");
if(isset($_GET['name'])){
$name=$_GET['name'];
$sql = "SELECT * FROM DVD where name='".$name."'";
}else $sql = "SELECT * FROM DVD";
foreach ($dbh->query($sql) as $row)
{
print 'dvds[index++]="#'.$row['name'] ."#".$row['director']. "#". $row['price']."#".$row['stock'].'#";<br>';
//dvds[index++]="#Life is Beautiful#dvd1#10.5#10#history#Roberto Benigni#";
}
/*** close the database connection ***/
$dbh = null;
}
catch(PDOException $e)
{
echo $e->getMessage();
}
?>
<form action="http://127.0.0.1/DVD_show.php" method="get">
<p>Please input DVD name: <input type="text" name="name" /></p>
<p><input type="submit" /></p>
</form>
'''
Upvotes: 1
Views: 302
Reputation: 753
The dbh-> query is wrong at this place as it only returns a statment but not something you can use with foreach
You first need to use the fetch() or fetchAll() methods
Please see changed code.
NOTE: If you have a HIGH number of results it is not recommended to use fetchAll as it loads the wohle dataset . then better use fetch() and while like shown in the example ar the link below.
<?php
try {
/*** connect to SQLite database ***/
$dbh = new PDO("sqlite:dvd.db");
//echo("ok");
if(isset($_GET['name'])){
$name=$_GET['name'];
$sql = "SELECT * FROM DVD where name='".$name."'";
}else $sql = "SELECT * FROM DVD";
//change this
$data = $dbh->query($sql) ->fetchAll();
foreach ($data as $row)
//changes end
{
print 'dvds[index++]="#'.$row['name'] ."#".$row['director']. "#". $row['price']."#".$row['stock'].'#";<br>';
//dvds[index++]="#Life is Beautiful#dvd1#10.5#10#history#Roberto Benigni#";
}
/*** close the database connection ***/
$dbh = null;
}
catch(PDOException $e)
{
echo $e->getMessage();
}
?>
<form action="http://127.0.0.1/DVD_show.php" method="get">
<p>Please input DVD name: <input type="text" name="name" /></p>
<p><input type="submit" /></p>
</form>
'''
please see:
https://phpdelusions.net/pdo_examples/select
Upvotes: 0