Jeet Gandhi
Jeet Gandhi

Reputation: 65

Getting the same value while using foreach in PHP

I have a row named trailers in a MySQL database and I am querying that table using PHP and storing the result of that query in a variable. After that ,I am using a foreach loop to parse through each value of the variable i.e. each and every trailer value in the table.

But the problem is, when I try to echo the values of the variable only the first value of the variable is getting echoed in place of all other value. This is the query.

$query1 = "SELECT title,img,ratings,star_cast,director,trailer,imdb_ratings,lifetime_collecton,whats_good,whats_bad,watch_or_not 
    FROM recent_movies";

$result1 = mysqli_query($connect, $query1);

This is the code of the for each loop

<?php 
foreach($result1 as $r):
    echo $r['trailer'];
endforeach;
?>

This is how the output looks like

Ten same values are getting printed instead of 10 different values.

Upvotes: 0

Views: 1291

Answers (1)

spencer7593
spencer7593

Reputation: 108370

Use the mysqli_fetch_array function to retrieve rows from a mysqli resultset.

Reference: http://php.net/manual/en/mysqli-result.fetch-array.php


 $result1 = mysqli_query($connect, $query1);
 while( $row = mysqli_fetch_array($result1,MYSQLI_ASSOC) ) {
     echo "<br> " . $row['title'] . " " . $row['ratings'] ;
 } 

Upvotes: 3

Related Questions