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)
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).';';
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With