Melvin Melvin - 1 month ago 6
PHP Question

PHP - SQL query only shows last result

This only returns the last one of my rows:



<?php
function all_infos_query() {
global $connection;

$query = "SELECT * ";
$query .= "FROM pages ";
$query .= "JOIN subjects ";
$query .= "ON pages.subject_id=subjects.id";
$infos_set = mysqli_query($connection, $query);
confirm_query($infos_set);
return $infos_set;
}


function infos_content() {
$infos_set = all_infos_query();

while($info = mysqli_fetch_assoc($infos_set)) {
$output = htmlentities($info["content"]);
$output .= " <br><br>";
}
mysqli_free_result($infos_set);
return $output;

}
?>

<?php echo infos_content() ?>





If I echo it like this it works (returns all rows):



<?php
$result = all_infos_query();

if($result === FALSE) {
echo "query failed: " . mysqli_error($connection);
}
else {
while($row = mysqli_fetch_array($result)) {
echo htmlentities($row['content']);
echo "<br><br>";
}
}
?>





What do I have to change in the function infos_content() to also get all the rows?
Thanks a lot!

Answer

This is because you redefine $ouput for every result

while($info = mysqli_fetch_assoc($infos_set)) {
                    $output = htmlentities($info["content"]); 
                    $output .= " <br><br>";

Instead, create $ouput outside the loop and append to it..

 $output ='';
while($info = mysqli_fetch_assoc($infos_set)) {
                    $output .= htmlentities($info["content"]); 
                    $output .= " <br><br>";