0

我有一个执行 mysql 查询的脚本,如果有行,它会编码一条消息。但我希望它对消息和查询的整个结果进行编码。这是我使用的代码:

<?php
include 'config.php';

// Connect to server and select databse.
mysql_connect("$dbhost", "$dbuser", "$dbpass")or die("cannot connect");
mysql_select_db("$dbname")or die("cannot select DB");


$id = @$_POST['id'];

// To protect MySQL injection (more detail about MySQL injection)
$id = stripslashes($id);
$id = mysql_real_escape_string($id);

$sql="Select * from table1 where ID='$id'";

$result=mysql_query($sql);

// Mysql_num_row is counting table row
$count=mysql_num_rows($result);
// If result matched $id and $mypassword, table row must be 1 row

if ($count == 1) {
     $message = array('status' => 'ok');
} 

header('Content-Type: application/json');
print '{"key":'. json_encode($message) .'}'; 
?>

所以我希望 JSON 看起来像:

{ "key": [ { "ID": "1", "NAME": "Test", "ADDRESS": "Test-street 123", "CONDITION": "false", "status": "ok" } ] }

那么我应该在 $message 中添加什么来实现这一点?

4

3 回答 3

1

您在那里缺少一个关联数组。

$message = array(array(
             "ID"        => "1",
             "NAME"      => "Test",
             "ADDRESS"   => "Test-street 123",
             "CONDITION" => "false",
             "status"    => "ok"
           ));
echo json_encode($message);
// [{"ID":"1","NAME":"Test","ADDRESS":"Test-street 123","CONDITION":"false","status":"ok"}]
于 2012-06-15T06:41:23.857 回答
0

您必须先获取查询结果,然后再尝试将其编码为 JSON。例如 :

$result=mysql_query($sql);
$message->key = array();
while( $row = $db->sql_fetchrow($result) ) {
    $message->key[] = $row; // or a specific dispatching of values in keys
}
于 2012-06-15T06:45:27.493 回答
0

使用 mysql_fetch_assoc 获取 mysql 结果,如下所示:-

if ($count == 1) {
    $message = mysql_fetch_assoc($result);
    $message['status'] = 'ok';
    $message = array($message);
    print '{"key":'. json_encode($message) .'}';
}
于 2012-06-15T07:06:55.150 回答