Click here to Skip to main content
15,886,026 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,

Recently ive been trying to use PDO for better security and I've come across an error that I cant fix. I think it may be related to the FetchAll() and/or foreach.

This is my code:

PHP
$type = general;

$db = Database::getConnection();
		$query = 'SELECT * FROM threads WHERE threadTopic=:threadTopic';
		$output = $db->prepare($query);
		$results = $output->execute(array(':threadTopic' => $type));
			if (count($results) > 0) {
				echo "<table class=\"discussion\">\n";
				echo "<tr><th colspan=2>Thread Name</th><th>Replies</th><th>Author</th></tr>\n";
					$rows = $output -> fetchAll();
					$name = $rows['threadName'];
					$body = $rows['threadBody'];
					$by = $rows['threadBy'];
					$date = $rows['dateCreated'];
					$sticky = $rows['threadSticky'];
					$image = '<img src="images/userIcon.gif"></img>';
					foreach ($rows as $row){
						echo "<tr>";
						echo"<td>".$image."</td>";
						echo"<td>".$name."<br>".$body."</td>";						
					}
					echo "</tr>\n";
					echo "</table>";
				}


The table and table headings are being displayed but the foreach is not working and is saying that my variables from the count are all undefined.

Help, please?
Posted

1 solution

After fetching the rows, you attempt to set variables directly from $rows, for example $name = $rows['threadName'];. But that won't work because 'threadName' is only a valid index when you use it on one row, not on the collection of rows. So, you have to fetch these variables inside your foreach (from $row), not outside the foreach:
PHP
echo "<table class=\"discussion\">\n";
echo "<tr><th colspan=2>Thread Name<<th>Replies</th><table><thead><th>Author</th></thead></table></tr>\n";
$rows = $output -> fetchAll();
foreach ($rows as $row){
    $name = $row['threadName'];
    $body = $row['threadBody'];
    $by = $row['threadBy'];
    $date = $row['dateCreated'];
    $sticky = $row['threadSticky'];
    $image = '<img src="images/userIcon.gif">';
    echo "<tr>";
    echo"<td>".$image."</td>";
    echo"<td>".$name."<br>".$body."</td>";				
}
echo "</tr>\n";
echo "</table>";
 
Share this answer
 
Comments
jba1991 23-Mar-15 18:37pm    
Thanks :D

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900