<?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对象啊。先谢谢了啊。
解决方案 »
- 如何从一个数组里拆出一部分作为一个新数组。
- 非常怪异的问题,用header()函数置多个cookie怎么只能写入最后一个cookie?
- 问下网站构筑的一些经验
- 用整则式如何匹配以alt=开头,空格结尾的字符串?POSIX语法
- 【xuzuning 】版主求教,有问题啊,各位高手围观。
- 小弟刚学PHP 请高手 用例子 解释一下这一块教程的意思
- 文本显示问题
- 发送邮件的程序中的问题
- php 连接远程mysql数据库 出现错误: Lost connection to MySQL server during query
- php http请求问题
- 列表页的标题是如何实现自动更新的
- 求PHP导出数据库视图的程序
这个就是解释后的 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);//返回一个数组