0

For a school project I needed to change my MySQL database to a MongoDB.

This is my old code that is working fine:

$movies = '';
$count = 0;

while($row_movie = mysqli_fetch_assoc($result)){
$count++;

$movies[$count] .= "{ value: '".$row_movie['naam']."', data:'".$row_movie['idProduct']."' }";

}

Now I made a foreach loop to handle the MongoDB collection:

$collection = $colProduct;
$products = $collection->find();

$result = $collection->find();

$movies = '';
$count = 0;
foreach($result as $row_movie){
   $count++;
   $movies[$count] .= $row_movie['naam'];
   print_r($movies);
}

But now I get the error: Notice: Undefined offset: 1 in D:\wamp64\www\examen.yvde.nl\currency-autocomplete.php on line 23

(this line: $movies[$count] .= $row_movie['naam'];)

I hope anyone can help me out! Thanks :)

Community
  • 1
  • 1
Yoran
  • 11
  • 3
  • 1
    `$movies` is an empty string at that point (0 characters). Are you sure you don't want it to be an array? Also, you're incrementing `$count` before that, so the first entry you set will be at index 1. PHP starts counting at 0, so you might want to move that `$count++` line further down a bit. – rickdenhaan Aug 20 '17 at 12:17
  • Additionally, you're *appending* to a non-existing entry by using `.=` instead of just `=`. – rickdenhaan Aug 20 '17 at 12:19
  • You should just use `$movies[] = ...` instead of trying to manually trying to set keys – Machavity Aug 20 '17 at 12:57

1 Answers1

0

You are appending string to array. change your code to

$movies = array();
$count = 0;

while($row_movie = mysqli_fetch_assoc($result)){
$count++;

$movies[$count] = "{ value: '".$row_movie['naam']."', data:'".$row_movie['idProduct']."' }"; //<---------remove .

}

In collection

$collection = $colProduct;
$products = $collection->find();

$result = $collection->find();

$movies = array();
$count = 0;
foreach($result as $row_movie){
   $count++;
   $movies[$count] = $row_movie['naam'];
   print_r($movies);
}
B. Desai
  • 16,092
  • 5
  • 22
  • 43