0

If I have an array $MovieDetails = array(); and it is populated by the query below with a foreach loop (5 elements; id, movie_year, genre, image, movie_name), how do I add another element (movie_rating) to the end of the array

$AllMovies = $con ->query
("
    SELECT id, movie_year, genre, image, movie_name FROM movies; 
");

 while($row = $AllMovies->fetch_object())  {
        $MovieDetails[] = $row;
    }  
3
  • 1
    add it to $row with $row['movie_rating'] before you add it to movieDetails Commented Apr 9, 2015 at 16:32
  • You could also make it easier to add it later, by changing it to $MovieDetails[$row['id']] = $row;. Then if you know the movie id, you can do $MovieDetails[$id]['movie_rating'] = $rating; Commented Apr 9, 2015 at 16:36
  • You're fetching the results as an StdClass object. You'll need to change to fetch_array() in order to let the posted answers work Commented Apr 9, 2015 at 17:56

3 Answers 3

3

Add movie rating into $row.

If you work with that as object, it's $row->movie_rating = 1.5

while($row = $AllMovies->fetch_object())  {
    $row->movie_rating = 1.5;
    $MovieDetails[] = $row;
}  

If you work with that as array, use fetch_assoc() and $row['movie_rating'] = 1.5

while($row = $AllMovies->fetch_assoc())  {
    $row['movie_rating'] = 1.5;
    $MovieDetails[] = $row;
}  
Sign up to request clarification or add additional context in comments.

4 Comments

I get back error ` Cannot use object of type stdClass as array`
should be fetch_array()
@McNoodles: If you work with that as object, there should be $row->movie_rating = 1.5. If you want array, change fetch_object for fetch_array.
@panther you should reflect this in your answer because your answer is incorrect at this point...
1

This way your row is an object

$AllMovies = $con->query("SELECT id, movie_year, genre, image, movie_name FROM movies;");
while($row = $AllMovies->fetch_object())  {
   $row->movie_rating = 'movieRating'; 
   $MovieDetails[] = $row;
}

If you want each row to be array, you should do:

while($row = $AllMovies->fetch_array())  {
   $row['movie_rating'] = 'movieRating'; 
   $MovieDetails[] = $row;
}

1 Comment

should be fetch_array()
0
$MovieDetails['movie_rating'] = $movie_rating; 

Comments

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.