0

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.

5
  • Mysqli_query returns true or false. Use mysqli_fetch_array Commented Apr 29, 2017 at 17:46
  • You need to fetch the data before you loop through it !!! Commented Apr 29, 2017 at 17:46
  • 1
    @Akin It returns a mysqli_result for a SELECT query. Commented Apr 29, 2017 at 17:58
  • @ForDev mysqli_result implements Traversable, so you can use it with foreach. Commented Apr 29, 2017 at 18:00
  • What version of PHP are you running? Using foreach with mysqli_result was added in 5.4.0. Commented Apr 29, 2017 at 18:01

1 Answer 1

3

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'] ;
 } 
Sign up to request clarification or add additional context in comments.

5 Comments

echo "<br>" . $row['title'] . " " . $row['ratings']; ;-) what you have now will throw a parse error. Least, I think lol
php.net/manual/en/class.mysqli-result.php says: 5.4.0 Iterator support was added, as mysqli_result now implements Traversable.
I don't think this'll work, you gotta put $row['title'] and $row['ratings'] into curly braces (i.e. {$row['ratings']})
@Fred-ii... please excuse my bad habitual Perl tendencies. I have made a correction. (Maybe I should stick to answering Perl DBI/DBD questions.)
@spencer7593 hehe, not a problem, just thought I'd let you know. And please continue with what you do and not limit yourself to other areas ;-) Cheers

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.