Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

Is there any possible way to get a data from a DB using MYSQL and store it in javascript Array.

Thanks in Advance

share|improve this question

4 Answers

Fetch it as an associative array, and then use json_encode to create a JavaScript array, stored in a string.

share|improve this answer

.

// first, build your query:
$sql = "SELECT name, email FROM users";

$result = mysql_query($sql);

// then build up your data
$rows = array();

while ($row = mysql_fetch_assoc($result)) {
    $rows[] = $row;
}

//then write it in a way Javascript can understand:

echo "<script type=\"text/javascript\">\n"
    . "var users = " . json_encode($rows) . ";\n"
    . "</script>";
share|improve this answer
<?php
$arr = array ('a'=>1,'b'=>2,'c'=>3,'d'=>4,'e'=>5); 
// of course this array can be created by looping through your mysql result set
// and doing a mysql_fetch_assoc
// for example, $sql = your query here 
// mysql_fetch_assoc($result); etc

echo json_encode($arr);
?>

{"a":1,"b":2,"c":3,"d":4,"e":5}

Then you can do something like

<script type="text/javsacript">
var abc = "<? echo json_encode($arr);?>";
</script>

OR

echo '<script type="text/javsacript">
        var abc ="'.json_encode($arr).'";
    </script>';
share|improve this answer

Actually this is a pretty vague question, but I think AJAX is what you're looking for.

EDIT: Of course JSON will workout too and might even be more straight forward...

share|improve this answer
 
you don't necessarily have to be making asynchronous calls to want to get info from a database into javascript! –  nickf Sep 22 '09 at 7:34
 
Mkkay, maybe AJAX is a bit of breakin a fly on the wheel... –  KB22 Sep 22 '09 at 7:36

Your Answer

 
discard

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.