我有以下php代码,我希望从查询结果开始打印 用[或{,但我得到这个结果“\ u0633 \ u064a \ u0627 \ u0631 \ u0627 \ u062a”
<?php
mysql_connect("localhost", "root", "password")
or die(mysql_error());
mysql_select_db("db") or die(mysql_error());
$result = mysql_query(" select part_name from Services_parts where part_id= 1 ")
or die(mysql_error());
while( $row = mysql_fetch_array( $result ) )
{
echo json_encode($row['part_name']) ;
}
?>
答案 0 :(得分:3)
如果你想要一个数组输出作为JSON然后将你的行添加到一个数组然后像这样json化数组
<?php
mysql_connect("localhost", "root", "password") or die(mysql_error());
mysql_select_db("db") or die(mysql_error());
$result = mysql_query(" select part_name from Services_parts where part_id= 1 ") or die(mysql_error());
$j_out = array();
while( $row = mysql_fetch_array( $result ) )
{
$j_out[] = $row['part_name'];
}
echo json_encode($j_out);
?>
如果您想要一个包含结果数组的对象,请执行此操作
<?php
mysql_connect("localhost", "root", "password") or die(mysql_error());
mysql_select_db("db") or die(mysql_error());
$result = mysql_query(" select part_name from Services_parts where part_id= 1 ") or die(mysql_error());
$j_out = new stdClass();
while( $row = mysql_fetch_array( $result ) )
{
$j_out->part_names[] = $row['part_name'];
}
echo json_encode($j_out);
?>
实际上,因为您只从数据库中获取一行,所以可以执行此操作,从而无需使用不必要的循环并使返回的对象更容易在javascript中处理。
<?php
mysql_connect("localhost", "root", "password") or die(mysql_error());
mysql_select_db("db") or die(mysql_error());
$result = mysql_query(" select part_name from Services_parts where part_id= 1 ") or die(mysql_error());
$row = mysql_fetch_array( $result );
$j_out = new stdClass();
$j_out->part_name = $row['part_name'];
echo json_encode($j_out);
?>
请不要使用
mysql_
数据库扩展,不推荐使用(在PHP7中永远消失) 特别是如果您只是学习PHP,请花时间学习PDO
或mysqli_
数据库扩展, and here is some help to decide which to use