Apply php/MySql while loop in javascript object [c

2019-09-19 16:18发布

问题:

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:

<?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 *.)