Because $result is defined in the if statement, itâs local to that statement. Take your whole while statement and move it inside the catch after the $pdo->quote statement.
try
{
$pdo = new PDO('mysql:host=localhost;dbname=ijdb','user','password');
$pdo->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
$pdo->exec('SET NAMES "utf8"');
}
catch (PDOException $e)
{
$error = 'Error Unable to connect at this time please try later';
include 'error.html.php';
exit();
}
try
{
$sql = 'SELECT joketext FROM joke';
$result = $pdo->quote($sql);
while($row = $result->fetch())
{
$jokes[] = $row['joketext'];
}
}
catch (PDOException $e)
{
$error = 'Error fetching jokes: '.$e->getMessage();
include 'error.html.php';
exit();
}
include 'jokes.html.php';
First of all Thank You!!
Here`s the response I got after the change:
Fatal error: Call to a member function fetch() on a non-object in C:\xampp\htdocs\yankproject\listjokes\index.php on line 19
my NetBeans IDE is not accepting âendforeachâ as shown in page 117 it instead gives me an error:
Parse error: syntax error, unexpected âendforeachâ (T_ENDFOREACH) in C:\xampp\htdocs\yankproject\listjokes\jokes.html.php on line 12. And, if I eliminate the endforeach command I get only the 5th joke and jokes 1 to 4 are missing. Any ideas?
I actually caught the typo. I used a ; instead of : at the end of the foreach statement. But I thank you guys . This is an awesome forum, I am grateful.
Do you understand why the â;â stopped it at 1 joke? In case not, the ; is a terminating character, so it terminated your foreach statement which would typically loop over each joke in $jokes after processing the first one. That is why you only got one joke when using â;â instead of â:â.
I had left off learning for a little while and trying the same code again and I am past the colon semicolon issue, but still getting this error: kindly comment
Notice: Undefined variable: jokes in C:\xampp\htdocs\jokes\home\jokes.html.php on line 8
Warning: Invalid argument supplied for foreach() in C:\xampp\htdocs\jokes\home\jokes.html.php on line 8
Youâre getting that error because the foreach is expecting an array to work with, it will have received a string instead as you probably had an empty result set returned by a query. Before doing any SELECT query, set up the variable that youâre going to use for the result set as an empty array eg, say youâre going to get a list of users who matches criteria x, y and z, and was going to place the result set into $da_users Before running the query you would do:
$da_users = array();
That will set up the $da_users variable as an empty array. If there was a result set returned then youâd load it into $da_users as normal, if there was no result set returned then the foreach will see what itâs expecting to be given to work with, an array, albeit en empty array.