【问题标题】:how to run an sql query against all items in array php如何对数组php中的所有项目运行sql查询
【发布时间】:2021-02-23 00:12:44
【问题描述】:

我的 PHP 脚本应该从 API 接收不确定数量的 JSON 数据,将其存储在一个数组中,然后对数组中的每个项目运行 SQL 查询。然后将查询作为 JSON 对象返回。

我的 API 如下所示:

if($_POST(['id'])){
    $id= $_POST['id'];
    foreach($value as $id){
        $sql = "SELECT id, header, body FROM `messages` WHERE id= $id";
        
        $stmt = $conn->prepare($sql);
        $stmt->bind_param("s", $id);
        $stmt->execute();
        while ($row = mysqli_fetch_assoc($stmt)) {
            $response = $row ['id'];
            $response = $row ['header'];
            $response = $row ['body'];
        }
        $stmt->close();
    }

    return json_encode($response);
}

对我来说,这似乎效率很低,必须有一个 SQL 函数来检查数组中的所有变量。

我需要我的 JSON 看起来像这样

{
    "resoponse": {
        "check": "check"
    },
    "code": [{
            "id": "id",
            "header": "header",
            "body": "body"
        },
        {
            "id": "id",
            "header": "header",
            "body": "body"
        },
        {
            "id": "id",
            "header": "header",
            "body": "body"
        }
    ]
}

我正在使用改造/gson 将 JSON 返回到运行 kotin 的 android 应用程序,所以如果我遗漏了什么,请告诉我。

感谢您的宝贵时间。

【问题讨论】:

  • 如果是 id 的集合,可以使用 where in 子句

标签: php mysql mysqli retrofit


【解决方案1】:

此代码可能会对您有所帮助,

$id= $_POST['id'];
$resoponse = array();
$array_push = array();
// foreach($value as $id){
    $sql = "SELECT id, header, body FROM `messages` WHERE id= ?";
    
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("s", $id);
    $stmt->execute();
    while ($row = mysqli_fetch_assoc($stmt)) {
        $response['id'] = $row ['id'];
        $response['header'] = $row ['header'];
        $response['body'] = $row ['body'];
        $array_push[] = $response; 
    }
    $stmt->close();
// }

$return = array("resoponse"=>array("check"=>"check"),"code"=>$array_push);

return json_encode($return);

【讨论】:

  • 在开始 foreach 循环之前初始化 array_push 变量 $array_push = array();
【解决方案2】:

我真的不知道我在做什么。您要做的就是将 JSON 对象转换为数组并循环遍历数组。

它应该看起来像这样。(这个例子来自 w3 学校)

$jsonobj = '{"Peter":35,"Ben":37,"Joe":43}';

$arr = json_decode($jsonobj, true);

foreach($arr as $key => $value) {
  echo $key . " => " . $value . "<br>";
}

https://www.w3schools.com/php/php_json.asp

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-14
    • 1970-01-01
    • 1970-01-01
    • 2016-07-07
    相关资源
    最近更新 更多