Page 1 of 1

populating javascript array with mysq data

Posted: Mon Feb 28, 2011 3:47 pm
by gamebit07
Hi everyone,
I have mysql databse and I wish to populate the data into javascript array, I have tried the follwoing but it is not working, please share your insights:

Code: Select all

<html>
<script type="text/javascript" charset="utf-8">
var First = [];
<?php
	$host = "localhost"; $user = "root"; $pass = "";  $db = "mydb"; 
	// open connection 
	$con = mysql_connect($host, $user, $pass) or die ("Unable to connect!"); 
        for($i = 1;$i<=1000;$i++)
	{
            $query = "SELECT * FROM question WHERE id = $i" ;
             // execute query 
		$result = mysql_query($query) or die ("Error in query: $query. ".mysql_error()); 
		$row = mysql_fetch_row($result);
		[u]print"First[<?$i?>] = <? $row[1] ?>"; // HERE I TRY TO POPULATE THE ARRAY[/u]
           }
                mysql_free_result($result); 
	 // close connection 
	      mysql_close($con); 	
	?>
</script>
</html>
let me know where i went wrong.
Thanks!!

Re: populating javascript array with mysq data

Posted: Mon Feb 28, 2011 4:39 pm
by AbraCadaver
That is whacked out code dude. You are doing 1000 queries and some may return no results. Try this (not tested). Assuming that the first column is the id, if not then use $row['id'] instead of $row[0]:

Code: Select all

<script type="text/javascript" charset="utf-8">
    var First = new Array();
    <?php
    $host = "localhost"; $user = "root"; $pass = "";  $db = "mydb";
    $con = mysql_connect($host, $user, $pass) or die ("Unable to connect!");
    $query = "SELECT * FROM question WHERE id BETWEEN 1 AND 1000" ;
    $result = mysql_query($query) or die ("Error in query: $query. ".mysql_error());

    while($row = mysql_fetch_array($result, MYSQL_NUM)) {
        echo "First[" . $row[0] . "='" . $row[1] . "';";
    }
    ?>
</script>
Or this other way with json data may work:

Code: Select all

<?php
$host = "localhost"; $user = "root"; $pass = "";  $db = "mydb";
$con = mysql_connect($host, $user, $pass) or die ("Unable to connect!");
$query = "SELECT * FROM question WHERE id BETWEEN 1 AND 1000" ;
$result = mysql_query($query) or die ("Error in query: $query. ".mysql_error());

while($row = mysql_fetch_array($result, MYSQL_NUM)) {
    $data[$row[0]] = $row[1];
}
$json_data = json_encode($data);
?>
<script type="text/javascript" charset="utf-8">
    var First = eval('(' + <?php echo $json_data; ?> + ')');
</script>

Re: populating javascript array with mysq data

Posted: Mon Feb 28, 2011 5:55 pm
by pickle
This is not General Discussion. This is mostly PHP-Code, so I'm moving the thread.