js遍历mysql,在javascript对象中循环应用php/MySql

该博客展示了如何从PHP中获取MySQL查询结果,并将这些数据转换为JSON格式,用于在JavaScript中创建动态对象。示例代码包括连接数据库,执行查询,收集结果并使用json_encode输出,强调了只选择必要的列以提高效率。
摘要由CSDN通过智能技术生成

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.

解决方案

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;

}

?>

// now output the collected results

var treeData = <?php echo json_encode($rows); ?>;

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值