The php/html file I am working on is laid out in this way.
// connect to DB $connection
foreach($connection-query($sql) as $row)
I'm getting the error 'Invalid argument supplied for foreach()' when I run this page. Can I not break out of the php and go into html and then come back to my php using the $connection variable created in the upper php code? Or once I break out with ?> is that it, all variable can not be picked back up again futher down in the page?
I can't think of another reason because I have used that exact foreach loop in another file and it worked fine.
This is the code I wrote at first and it's working with any problems. But when tried the same thing with my newer program I'm getting the error 'Invalid argument supplied for foreach()'. Again the program below works just fine. Any ideas?
// open a DB connectiong
$dbn = 'mysql:dbname=popcount;host=127.0.0.1';
$user = 'user';
$password = 'password';
$connection = new PDO($dbn, $user, $password);
catch (PDOException $e)
echo "Connection failed: " . $e->getMessage();
<form method='post' action="">
Please Enter Customer id# <input name='id' type='text' /> <input type='submit' />
$id = $_POST['id'];
$sql = "SELECT full_name FROM customers WHERE id# =".$id;
foreach($connection->query($sql) as $row)
The number sign # acts like a comment in MySQL, in your case it will affect the query by returning all the rows instead of selecting by id. But this should not return the Invalid argument supplied for foreach() error, it seems that your query returned boolean FALSE.
To understand what is going on, use a try/catch block and exceptions. For example:
Note: using die() and printing error messages directly in page is good in development stage, while in production you should append all error codes and messages to the error log file and return a simple message, without details.
Thanks I'll give that a try. I'm not actually using a '#' in my code. I just didn't want to post the actualy code because it's for my State's correctional DEPT. I just didn't understand why the foreach loop worked with that same argument in my test code but not in my development file.