PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!
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:
<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!!
Last edited by califdon on Mon Feb 28, 2011 3:55 pm, edited 1 time in total.
Reason:Moderator added syntax=php tags to make code readable. Note to poster, please always do this.
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]:
<?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>
mysql_function(): WARNING: This extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQLextension should be used. See also MySQL: choosing an API guide and related FAQ for more information.