Loading a Javascript array with MYSQL database data

Suppose I have a javascript array "userName". I want to load it from a database table named "user".

Can anyone help with an idea or sample code?

thanks

+6
javascript php mysql
source share
4 answers

Use ajax and php as intermediates:

  • Define an empty JS array:

    var myarray = new Array();

  • use ajax to call your php script, javascript will parse the PHP output (note that it uses a prototype library):

      new Ajax.Request('myfile.php', { onSuccess : function(xmlHTTP) { eval(mlHTTP.responseText); } }); 
  • Write your PHP code to capture data and print JS code (it must be valid javscript!):

     $i=0; $q=mysql_query('select ..'); while($row=mysql_fetch_array($q)){ echo "myarray[".$i."]='".$row['data']."';"; $i++; } 
  • You can verify that your Js array contains data:

     alert(myarray.length); 

hope this helps.

+5
source share

This creates a global user variable on your page.

 <?php $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); ?>; </script> 

If you are looking for a dynamic AJAXy solution, follow the AJAX instructions.

+4
source share

You will need 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 a name and field identifier, SELECT name, id FROM user ). Then you can get all the information from db using mysql_fetch_assoc() or any other mysql extraction function. Now you need to echo your javascript data on your site, formatted as an array. This is hard to do right, but you can get help from json_encode .

To populate your array with usernames, you would do something like this.

 <html> <head> <script type="text/javascript"> var userName = <?php // Connect to MySQL //mysql_connect(); //mysql_select_db(); $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 </script> </head> 
+4
source share

The best way to do this is simply to get your data in your php code and then "write" javascript code to generate the array in php.

A short example:

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

My code may be pretty wrong, just give you a quick example.

You can also do this in a more elegant way using json.

+1
source share

All Articles