无法从mysql varchar中获取json但是int

时间:2015-04-24 15:27:34

标签: php mysql json

我有一个MySQL数据库拥有一个表“新闻”,其中包含“ID”(Int(15)),“titel”(varchar(255))等等。

以下代码让我得到列“id”的json。但是,如果我想获得“titel”这一列,我就不会从这个PHP中获得任何东西。

$con=mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");

$sql = "SELECT `titel` FROM `news` ORDER BY `datum` DESC";
$result = mysql_query($sql);
$json = array();

if(mysql_num_rows($result)){
while($row=mysql_fetch_assoc($result)){
$json['news'][]=$row;
}
}
mysql_close($con);
echo json_encode($json);

这里phpMyAdmin的表结构为表(xx = empty)

Name   Type         Collation       Attributes   Null   Default     

id     int(15)      xx              UNSINGED     No     None
titel  varchar(255) lati1_swedi..   xx           No     xx

1 个答案:

答案 0 :(得分:0)

将行$json['news'][]=$row;更改为$json['news'][]=array_map('utf8_encode', $row);解决了这个问题。数据库表中存在ä,ö.... 等字符。

$con=mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");

$sql = "SELECT `titel` FROM `news` ORDER BY `datum` DESC";
$result = mysql_query($sql);
$json = array();

if(mysql_num_rows($result)){
while($row=mysql_fetch_assoc($result)){

$json['news'][]=array_map('utf8_encode', $row);
}
}
mysql_close($con);
echo json_encode($json);