动态构造INSERT语句后类型转换失败?

时间:2017-03-14 23:57:42

标签: php sql json postgresql type-conversion

我试图基于JSON键/值对动态创建INSERT语句,其中$ key是字符串或整数数据类型的数据库字段,$ value是整数或字符串。我之前没有在将数字字符串插入Postgres时出现问题,但它失败了。

示例:

$json = '{"stringField":"string","intString":"42"}';
$columns = $values = '';
foreach (json_decode($json, true) as $key => $value) {
    if ($value != NULL) {
        $columns .= $key . ', ';        
        $values .=  "'" . $value . "', ";
    }
}
$query = ('INSERT INTO table ('.rtrim($columns, ', ').') VALUES ('.trim($values, ', ').');');

2 个答案:

答案 0 :(得分:1)

这是更干净的PHP:

$json = '{"stringField":"string","numberField":"42"}';
$columns = $values = '';
foreach (json_decode($json, true) as $key => $value) {
    if ($value !== NULL) {
        $columns .= $key . ', ';
        $values .= is_numeric($value) ? $value : "'" . $value . "', ";
    }
}

$query = 'INSERT INTO table ('.rtrim($columns, ', ').') VALUES ('.trim($values, ', ').');';

请考虑逃避你的价值观。

答案 1 :(得分:1)

问题结果是其中一个值实际上是一个 float 数字字符串,在插入整数字段时失败,如果它是一个数字字符串,则将该值四舍五入。 is_numeric检查可避免将字符串字段转换为0

<强>解决方案:

$json = '{"stringField":"string","floatString":"42.0","intString":"42"}';
$columns = $values = '';
foreach (json_decode($json, true) as $key => $value) {
    if ($value != NULL) {
        $columns .= $key . ', ';        
        $values .= is_numeric($value) ?  round($value) . "," : "'" . $value . "', ";
    }
}
$query = ('INSERT INTO table ('.rtrim($columns, ', ').') VALUES ('.trim($values, ', ').');');