MySQL Query to Json

来源:互联网 发布:农村淘宝电子商务ppt 编辑:程序博客网 时间:2024/05/02 00:56

/******************by garcon1986*********************/

 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<title></title>
</head>
<body>
<?php
$connect = mysql_connect("localhost","root","") or die(mysql_error());
mysql_select_db("crm1_7");
$query = "select id,firstname,lastname from user";
//$query = "select * from user";
$results = mysql_query($query) or die(mysql_error());
//以下代码的array显示方式是Array ( [0] => 1 [id] => 1 [1] => piman [firstname] => piman [2] => piman [lastname] => piman )
/*while($row = mysql_fetch_array($results)){
//print_r() 使array以Array ( [0] => 1 [id] => 1 [1] => piman [firstname] => piman [2] => piman [lastname] => piman ) 形式显示
print_r($row);
//json_encode() 以json形式显示
echo json_encode($row);   
}
*/
//以下代码array的显示方式是{"id":"1","firstname":"piman","lastname":"piman"}
/*while($row = mysql_fetch_array($results, MYSQL_ASSOC)){
echo json_encode($row);
}*/
//或者{"id":"1","firstname":"piman","lastname":"piman"}
while($row = mysql_fetch_assoc($results)){
echo json_encode($row);
}
?>
</body>
</html>

例子2:

<!DOCTYPE html>
<html>
<head>
<script src="jquery1.4.js"></script>
</head>
<body>
<?php
$conn = mysql_connect("localhost","charles","charles");
mysql_select_db("crm1204", $conn);
$query = "select * from entreprise";
$result = mysql_query($query);
$response = "[";
while($row = mysql_fetch_array($result)){
$response .= "{'nom':'".$row['nom']."', 'entreprise_id':'".$row['entreprise_id']."'}";
}
$response .= "]";

echo $response;
?>
</body>
</html>

结果:
[{'nom':'e1', 'entreprise_id':'1'}{'nom':'e2', 'entreprise_id':'2'}]

原创粉丝点击