Jump to content

foreach not producing desired result


mellis95

Recommended Posts

I have the following foreach that should output two rows, but only outputs the first result. Can someone help me see what I am missing?

 

Here is the query:

SELECT DISTINCT m.lname AS plname, m.fname AS pfname FROM tbl_schedule AS s LEFT JOIN members AS m ON m.id=s.id

 

Which outputs the following from the command line:

+---------+----------+

| plname  | pfname  |

+---------+----------+

| Boring  | David A. |

| Bateman | Megan    |

+---------+----------+

2 rows in set (0.00 sec)

 

Here is the foreach:

 

echo "<table class='petite'><tr>";

   foreach($result as $name){
echo "<th>" . $name . "</th>";
    	}
    	echo "</tr>";

 

Which outputs the following:

Boring David A.

 

Thank you in advance for the help.

 

Matt

 

Link to comment
https://forums.phpfreaks.com/topic/190801-foreach-not-producing-desired-result/
Share on other sites

Each call to a mysql_fetch_xxxxx() instruction retrieves ONE row from the result set (like it states in the php documentation.) You would need to use the mysql_fetch_xxxxx instruction in a loop (like the examples in the php documentation show) to retrieve each row in a result set.

Thanks PFMaBiSmAd. I was looking for the problem in the wrong place. The following code, per your suggestion, fixes the issue:

 while ($row = $query2->fetch(PDO::FETCH_ASSOC)) {
   foreach($row as $name){
  		echo "<th>" . $name . "</th>";
    	}
    	}
    	echo "</tr>";

 

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.