gpt4 book ai didi

php - JSON编码mysql查询

转载 作者:行者123 更新时间:2023-11-29 14:25:32 24 4
gpt4 key购买 nike

我有一个执行 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”,
“名称”:“测试”,
"ADDRESS": "测试街123号",
“条件”:“假”,
“状态”:“正常”
}
]
}

那么我应该在 $message 中添加什么来实现这个目的?

最佳答案

那里缺少一个关联数组。

$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"}]

关于php - JSON编码mysql查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11045682/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com