I am a newbie to MySQL. I want to transfer data from MySQL table to javascript. I want to create a multidimensional array in javascript using the table in MySQL. This multidimensional array is to be used in other functions for calculation. Is there any way to do it using PHP or JSON?
4
-
Yes, there is. More than just one, actually. Do you want to know something else?MaxArt– MaxArt2012-07-31 16:17:38 +00:00Commented Jul 31, 2012 at 16:17
-
1Regardless of WHEN you do the data transfer, you'd still use php.net/json_encodeMarc B– Marc B2012-07-31 16:18:00 +00:00Commented Jul 31, 2012 at 16:18
-
1THere are a number of ways to attack this. Are you trying to pass the data along with intitial page load or after the page load?Mike Brant– Mike Brant2012-07-31 16:18:25 +00:00Commented Jul 31, 2012 at 16:18
-
1my recomendation go to youtube and see some basic tutorial of AJAX (is a technology where you can merge JAVASCRIPT, PHP and MySQL)jcho360– jcho3602012-07-31 16:23:11 +00:00Commented Jul 31, 2012 at 16:23
Add a comment
|
3 Answers
Read records from your database table in PHP page and Create JSON And send it to Javascript. JSON can hold any level of hierarchical data.
A sample JSON may looks like this
[
{
"Customers": [
{ "Name": "Steve", "ID": "A12" },
{ "Name": "Mark", "ID": "A22" }
]
}
]
JsonLint is a useful tool when working with JSON data. It can validate JSON.
Comments
If you want to populate the javascript data on initial page load, you can do something like:
<?php
// get stuff from DB
$array_from_db = ... // some value determined via MySQL queries
?>
<script type="text/javascript">
var db_array = <?php echo json_encode($array_from_db); ?>
</script>
<?php
// more PHP stuff
Comments
This should work
<?php
var query=mysql_query("SELECT fields FROM table WHERE condition");
while($obj=mysql_fetch_array($query)){
arr[]=$obj
}
$array=json_encode($arr);
?>
<script type="text/javascript">
var db_array = <?php echo $array; ?>
</script>
3 Comments
tadman
Please do not suggest using
mysql_query. Use mysqli or PDO.Juan Gonzales
That's a petty thing to get a down vote for. It's a proof of concept that could easily be manipulated to the use of PDO or mysqli.
tadman
SQL injection is no joke. Careers are destroyed. Companies are ruined. There are far too many reckless examples of SQL using
mysql_query out there. The last thing the internet needs is one more. I'm sorry, but people refer to StackOverflow constantly and it must set a good example or it's doing more harm than good.