2

I am trying to convert an array from PHP to Javascript. My table has a lot of columns. The first 2 are id (INT) and name (VARCHAR).

This is my PHP code:

$sql = 'select * from foodlist';
$query1 = mysqli_query($conn, $sql);
$javascriptarray = mysqli_fetch_array($query1);

This is my javascript code:

var foodArray = <?php echo json_encode($javascriptarray) ?>;

First I tried this:

jQuery(this).val(foodArray.id);

It outputs the id of the first row. How do I produce the id of the second row? Normally I would do something like this, but this produces nothing.

jQuery(this).val(foodArray[0]);

Thank you in advance for the help and tips.

2
  • How does foodArray look like ?
    – Jose Rojas
    Commented Feb 11, 2018 at 17:34
  • 1
    foodArray.id[1] if you're only looking for the id on the second row. Otherwise, if you want the id from all rows, you would do that with a for loop. Commented Feb 11, 2018 at 17:34

1 Answer 1

1

The problem is that fetch_array only returns one row at a time. You need to loop through it with a while loop.

$array = array();
while($row = mysqli_fetch_array($query1)){
    array_push($array, $row);
}

then in js..

var foodArray = <?php echo json_encode($array) ?>;

To validate print footArray to the console with console.log(foodArray); You'll see that what you currently have is just one row of results.

2
  • 1
    On php.net i saw it was array_push() not push_array(). Other than that it was a big help. This was the biggest obstacle holding my project back. Thank you very much for your help and your time.
    – JeffreyR
    Commented Feb 11, 2018 at 19:54
  • Oops you’re right :) I’ll edit for other users. Glad I could help! Commented Feb 11, 2018 at 19:55

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.