I would like to take the following php/mysql loop, and apply the results: $test,$test1,$test2 to the var Data object in the javascript code. This will make the var Data dynamic, pulling its data to construct the object form the database.
1 Answer
<?php
include("regDBConnect.php");
// collect all the results
$rows = array();
$result1 = mysql_query("SELECT * FROM Phase where Pid = 1", $db) or die("cannot select");
while($row = mysql_fetch_array($result1)) {
$rows []= array(
'id' => $row['id'],
'parent' => $row['parent'],
'name' => $row['name'],
);
/*
if you remove the line above and uncomment this instead,
javascript objects will see all the properties you selected from the DB
*/
// $rows []= $row;
}
?>
<script type="text/javascript">
// now output the collected results
var treeData = <?php echo json_encode($rows); ?>;
</script>
Note that what I said about PDO/MySQLi still applies, this is just a minimal example to answer this specific question. (And in general, you should SELECT only those columns you will need, not *
.)
-
Thanks soo much. It worked like a charm :) And I will start learning to code using the PDO or MySQLi.user1684586– user168458609/21/2012 14:53:51Commented Sep 21, 2012 at 14:53
$res1
) into an array, and output it withvar treeData = <?php echo json_encode($rows); ?>;
. And please stop writing new code with the ancient mysql_* functions. They are no longer maintained and community has begun the deprecation process. Instead you should learn about prepared statements and use either PDO or MySQLi. If you care to learn, here is a quite good PDO-related tutorial.