Home » Php » php – Load Javascript array with MYSQL database data

php – Load Javascript array with MYSQL database data

Posted by: admin July 12, 2020 Leave a comment


suppose i have an javascript array “userName”.I want to load it from a database table named “user”.

Can anyone help with idea or sample code?


How to&Answers:

Use ajax and php as an intermediate :

  1. Define an empty JS array :

    var myarray = new Array();

  2. use ajax to call your php script, javascript will eval the output by PHP (note this uses prototype library):

     new Ajax.Request('myfile.php', {
        onSuccess : function(xmlHTTP) {
  3. Write your PHP code to grab data and print JS code (it must be valid javscript !) :

    $i=0; $q=mysql_query('select ..');
        echo "myarray[".$i."]='".$row['data']."';";
  4. You can check that your Js array contains data :


hope this helps.


You’ll have to use the mysql_connect(), mysql_select_db() functions in PHP to connect to your db. After that use mysql_query() to SELECT the fields in your user table (if your user table has the fields name and id, SELECT name, id FROM user). Then you can fetch all infos from the db with mysql_fetch_assoc() or any other mysql fetch function. Now you need to echo your data into the javascript on your website, formatted as an array. This is complicated to get right, but you can get help from json_encode.

To fill your array with the user names, you’d do something like this.

    <script type="text/javascript">
        var userName = <?php
            // Connect to MySQL
            $d = mysql_query( "SELECT name, id FROM user" ) or die( mysql_error() );
            $usernames = array();
            while( $r = mysql_fetch_assoc($d) ) {
                $usernames[] = $r['name'];
            echo json_encode( $usernames );
        // Do something with the userName array here


This creates a global user variable in your page.

    $user = /* get information from database the way you usually do */;
    // $user == array('id' => 1, 'name' => 'foo', ...);

<script type="text/javascript" charset="utf-8">
    var user = <?php echo json_encode($user); ?>;

If you’re looking for a dynamic AJAXy solution, follow some tutorials about AJAX.


The best way to do that simply is to get your data in your php code, and then “write” the javascript code to generate the array in php.

A short example would be :

echo "a = new Array();";
foreach($row in $results)
  echo "a[$row[0]] = $row[1];";

My code could be quite incorrect, it’s juste to give you a quick example.

You could also do that in a more elegant way, using json.