php-api-mysql或postgresql更新后的结果类型规范


php api mysql or postgresql result type specification for update post

我正在用我的PHP rest API从数据库中获取一条记录。

http://myapiyrl/product/get.php?id=20

结果:

{
   "id": "20",
   "name": "laptop",
   "color": "white",
   "price": "1200"
}

所以我想编辑这张唱片。我将此记录发布到post.php

http://myapiyrl/product/post.php
private function createUpdateQueryStringFrom($_POST){
    $attributes = array();
    foreach ($_POST as $key => $value)
        $attributes[] = " $key=$value ";
    $query_string = " UPDATE product ";
    $query_string .= " SET ";
    $query_string .= join(",", $attributes);
    $query_string .= " WHERE gid = ";
    $query_string .= $_POST["gid"];
    return $query_string;
}

此函数创建一个更新查询字符串,如下所示:

update product set id=20, name=laptop, color=black, price=1250 where id=20
    This gives error: pg_query(): Query failed: ERROR:  syntax error at or 
near "," ^name=laptop

我认为这个更新查询应该按列类型创建。如果列是字符串,它将介于(")之间,如果它不是数字。

update product set id=20, name="laptop", color="black", price=1250 where id=20

我该如何解决这个问题?我可以在从数据库获取时指定类型吗

{
   {"id": "20", "type": "number"}
   {"name": "laptop","type": "string"}
   {"color": "white","type": "string"}
   {"price": "1200","type": "number"}
}

您可以使用is_numeric检查值,并相应地添加引号:

foreach ($_POST as $key => $value)
    $attributes[] = is_numeric($value) ? " $key=$value " : " $key='"$value'" ";