0

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? Commented Jul 31, 2012 at 16:17
  • 1
    Regardless of WHEN you do the data transfer, you'd still use php.net/json_encode Commented Jul 31, 2012 at 16:18
  • 1
    THere 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? Commented Jul 31, 2012 at 16:18
  • 1
    my recomendation go to youtube and see some basic tutorial of AJAX (is a technology where you can merge JAVASCRIPT, PHP and MySQL) Commented Jul 31, 2012 at 16:23

3 Answers 3

3

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

-1

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

Please do not suggest using mysql_query. Use mysqli or PDO.
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.
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.