PHP foreach () function on query result returns only the last record in the table.
I've used PHP's mysql and mysqli procedural code for years, but I'm trying to learn how to use OOP. One of the simple projects I'm working on needs to return records from a MySQL database, but so far I'm not getting the results I expected.
I have a database in place with several tables, one of which is MtgsCities. I have used this database and table successfully in the past, and I have checked to confirm that it still holds 43 records, with only one field (of varchar(24) type) in each record. That solitary field is mtgCity. Having established a connection handler ($cnxn), I run the following four lines of code: Code:
foreach ($cnxn->query("SELECT * FROM MtgsCities") as $row); Quote:
Any ideas where I can go from here? |
Try your code without the semicolon at the end of the foreach line.
Long ago, when first learning C++, I read Bruce Eckel's books and he recommends placing the opening brace on the same line as the loop statement. Code:
foreach ($cnxn->query("SELECT * FROM MtgsCities") as $row);{ It's heretical I know, but I have avoided this common (and sometimes hard to find) problem since. |
Thank you, norobro! I can't tell you how many times I re-read those four lines looking for some kind of simple typo - and missed that extraneous semi-colon every time!
You know, I used to put the opening brace on the same line of all my loop and conditional statements, but changed to this format after reading a book about PHP and OOP. You're right - it does make the meddlesome semi-color so obvious! I may just change back to the way I used to do things. Thanks again! |
All times are GMT -5. The time now is 08:40 AM. |