Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I populate a javascript array with values from a database using PHP?

Tags:

javascript

php

I have to create a javascript array whose elements are fetched by php from a database. Is it possible? If so, how?

(I dont want to use ajax to do that)


2 Answers

Collect the values in an array and convert it to JSON with json_encode:

$array = array();
while ($row = mysql_fetch_assoc($result)) {
    $array[] = $row['key'];
}
echo 'var array = '.json_encode($array).';';
like image 69
Gumbo Avatar answered Jun 23 '26 18:06

Gumbo


Answer 1: yes, it can be done.

Answer 2: Here's how:

$js_array = "[";
$result = mysql_query("some query of yours");
while( $row=mysql_fetch_array($result, MYSQL_NUM) ) {
    $js_array .= $row[0]; // assuming you just want the first field 
                          // of each row in the array
    $js_array .= ",";
}
$js_array{ strlen($js_array)-1 } = ']';

echo "var db_array = $js_array ;";

Cheers!

like image 29
jrharshath Avatar answered Jun 23 '26 17:06

jrharshath