Join the Stack Overflow Community
Stack Overflow is a community of 6.6 million programmers, just like you, helping each other.
Join them; it only takes a minute:
Sign up

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)

share|improve this question
1  
Please give more detail on "What kind of dynamism" you are talking about. – NawaMan Sep 13 '09 at 5:18

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).';';
share|improve this answer

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!

share|improve this answer
    
I'm no php guy, but doesn't this add an extra comma to the array? – Kobi Sep 13 '09 at 6:12
    
@Kobi: It will, but the JavaScript engine won't complain. If you alert the contents of array [a, b, c,] to the screen with alert([1, 2, 3,]) the text "a, b, c," will be shown. – David Andres Sep 13 '09 at 6:45
1  
@Kobi: Actually, on closer inspection the line $js_array{strlen($js_array) - 1} = ']'; probably overwrites that last comma. – David Andres Sep 13 '09 at 6:46
    
@David: firefox complains. – nickf Sep 13 '09 at 8:33
<script language="javascript1.2">
var arr = new array(<?php 
$result = mysql_query("select .... ");
$count = mysql_num_rows($result);
if($count>0){
  for( $i=0;$i<$count-1;$i++) {
    $row = mysql_fetch_row($result);
    echo $row[0],',';
  }
  $row = mysql_fetch_row($result);
  echo $row[0],',';
}
?>);
</script>
share|improve this answer

If you can loop through the database contents, creating an array is simple:

echo "var myArray = [";

Loop through array here and add commas to separate values.

echo "];";

Your myArray variable will be available client-side. It should look something like:

var myArray = [1, 3, 2, 4];

Alternatively and to avoid an extra comma due to loop-based string concatenation, you can write the variable to the client as follows:

echo "var myArray = [];"

...and do the following for each data row:

echo "myArray.push($db_data);"

This is effective, though not quite as clean as the previous approach. You will end up with code similar to the following:

var myArray = [];

myArray.push(3);
myArray.push(5);
myArray.push(1);

alert(myArray); // will display "3, 5, 1"

My apologies for not being too familiar with PHP, but this is something that can be done with any server-side language.

share|improve this answer
    
right you are ! – jrharshath Sep 13 '09 at 6:02

Here is a solution that correctly deals with single quotes in the data:

First retrieve the database data, for example with mysqli_ functions:

$result = mysqli_query($con, $sql);
if (!$result) die(); // error handling comes here
$array = mysqli_fetch_all($result, MYSQLI_ASSOC);

Then convert it to JSON, escape single quotes and output the JavaScript:

$output = str_replace("'", "\'", json_encode($array));
echo "var array = '$output';";

Note that json_encode escapes backslashes (as it should) by doubling them. And it is normal that it does not escape single quotes, as it cannot know the context we put it in. So when we inject it in JavaScript, wrapping it in single quotes, we are also responsible for escaping the quotes.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.