<?php include("dbinfo.inc.php"); mysql_connect(localhost,$username,$password);
@mysql_select_db($database) or die( "Unable to select database");
$operation = $_GET['operation'];
$brand = $_GET['brand']; if($brand == 'hp'){ $query = "SELECT * FROM laptop WHERE name like '%" . $brand . "%'"; mysql_query("SET NAMES UTF8");
$result = mysql_query($query);
$num = mysql_num_rows($result);
mysql_close();
$i = 0;
while ($i < $num) {
$price = mysql_result($result,$i,"price");
$weight = mysql_result($result,$i,"weight");
$json = '{"laptops":{"price": "$price","weight": "$weight"}}';
$json_string = json_encode($json);
$obj = json_decode($json_string);
echo "$obj";
$i++;}
} else {
echo "error"; }?>
我现在想从数据库查询得到hp的price 和weight 的值,因为数据库中有很多,我想把得到的值,存成json的形式,然后编码和解码,在输出回来。有没有高手啊,用过php操作从数据库返回的json对象啊。先谢谢了啊。
这个就是解释后的 json 串了。就是你一楼的这个形式了。具体形式,得看你 json 前的是什么样子了。
我的现在这个流程是没有问题的,就是从数据库中得到数据后,我怎么写成json的形式的问题。
include("dbinfo.inc.php");
mysql_connect(localhost,$username,$password);
@mysql_select_db($database) or die( "Unable to select database");$operation = $_GET['operation'];
$brand = $_GET['brand'];
if($brand == 'hp'){
$query = "SELECT * FROM laptop WHERE name like '%" . $brand . "%'"; mysql_query("SET NAMES UTF8");
$result = mysql_query($query);
$num = mysql_num_rows($result);
mysql_close(); $i = 0;
while ($i < $num) {
$price = mysql_result($result,$i,"price");
$weight = mysql_result($result,$i,"weight");
$json = '{"laptops":{"price": "$price","weight": "$weight"}}';
$json_string .= json_encode($json); //连续输出
echo "$json_string";
$i++;
}
} else {
echo "error";
}
?>
在$json 中$price的值都不到,怎么回事啊。
连续输出的结果,还是{"laptops":{"price": "$price","weight": "$weight"}}{"laptops":{"price": "$price","weight": "$weight"}}的形式啊,这种形式并不是一个json的形式啊。
2 json_encode 只支持utf-8
$json = "{\"laptops\":{\"price\": \"$price\",\"weight\": \"$weight\"}}";
这是 json_encode 的结果你可以这样写:
$p->laptops->price = $price;
$p->laptops->weight = $weight;
echo json_encode($p);另外,你的数据库操作语句有误:
$result = mysql_query($query);
$num = mysql_num_rows($result);
mysql_close();
到数据库的连接都关闭了,后面怎么取值?
你在JS里可以直接得到/使用它。
var jsondata=<?php echo json_encode($array);?>;你的代码:
$json = '{"laptops":{"price": "$price","weight": "$weight"}}';
$json_string = json_encode($json);
$obj = json_decode($json_string);
这不是画蛇添足吗?
(array)json_decode($json_string);和json_decode($json_string,true);//返回一个数组