LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Software (https://www.linuxquestions.org/questions/linux-software-2/)
-   -   PHP foreach () function on query result returns only the last record in the table. (https://www.linuxquestions.org/questions/linux-software-2/php-foreach-function-on-query-result-returns-only-the-last-record-in-the-table-4175592376/)

qajaq 10-27-2016 04:30 PM

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);
{
  echo "The city is " . $row["mtgCity"] . ".<br />";
}

The result prints out only one line:
Quote:

The city is Worthington Springs.
Clearly the routine is reading the table, but is displaying only the last record in the table. I'm obviously missing something, but all the online searching I've done has not revealed anything helpful.

Any ideas where I can go from here?

norobro 10-27-2016 06:47 PM

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);{
    echo "The city is " . $row["mtgCity"] . ".<br />";
}

Makes it pretty obvious that the semicolon doesn't belong, doesn't it?

It's heretical I know, but I have avoided this common (and sometimes hard to find) problem since.

qajaq 10-27-2016 08:13 PM

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.