Apply php/MySql while loop in javascript object [closed]

痞子三分冷 提交于 2019-12-13 07:54:39

问题


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



来源:https://stackoverflow.com/questions/12531993/apply-php-mysql-while-loop-in-javascript-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!