PHP json_encode() 在数组元素周围添加额外的双引号

标签 php mysql

我有一个名为 $items 的数组,如下所示:

array   (
            0 => '{"id":"1", "qty":"1", "price":"12.51"}',
            1 => '{"id":"2", "qty":"2", "price":"25.02"}',
        )

我正在尝试构建一个 mySQL INSERT 语句,其中包含 $items 中的数据,如下所示:

$sql = 'INSERT INTO vals (id, items, timestamp) 
        VALUES (' . $id . ', "' . json_encode($items) . '", "' . date('Y-m-d H:i:s')  . '")';

但是,由于 json_encode() 在数组元素周围添加双引号,插入 mySQL 失败:

INSERT INTO
            vals
                    (
                        id,
                        items,
                        timestamp
                    )
        VALUES
                    (
                        1,
                        "[
                            "{\"id\":\"1\", \"qty\":\"1\", \"price\":\"12.51\"}",
                            "{\"id\":\"2\", \"qty\":\"2\", \"price\":\"25.02\"}"
                        ]",
                        "2015-11-26 20:31:02"
                    )  

问题出在大括号“{ ...data... }”之前/之后的双引号。

有没有办法将数组转换为字符串来消除这些额外的引号?

非常感谢您的指导!

编辑:

从下面的示例中,我尝试使用 mysqli 准备好的语句。

我正在执行以下操作:

$stmt->bind_param("i", (int) $id)

并且收到此错误:

ERROR: exception 'Symfony\Component\Debug\Exception\FatalErrorException' 
with message 'Call to a member function bind_param() on a non-object'

执行以下命令时我没有收到错误:

$stmt = $mysqli->prepare($sql)

所以我认为 $stmt 应该可以调用 bind_param() 。

我查看了 PHP 文档,认为我不需要对 $stmt 做任何其他事情。有人看到我缺少的东西吗?

最佳答案

您需要转义 json_encoded 字符串以便在查询中使用,或者使用准备好的语句并将值绑定(bind)到参数。

实际上需要对各个数组项进行引号,因为各个数组项实际上是字符串...因此您需要的只是转义整个值...

所以要么:

$sql = 'INSERT INTO vals (id, items, timestamp)
        VALUES (' . $id . ', "' . mysql_real_escape_string(json_encode($items)) . '", "' . date('Y-m-d H:i:s')  . '")';

或者更好的方法:

$json = json_encode($items);
$sql = 'INSERT INTO vals (id, items, timestamp) VALUES (?, ?, ?)';

/* Prepared statement, stage 1: prepare */
if (!($stmt = $mysqli->prepare($sql))) {
    echo "Prepare failed: (" . $mysqli->errno . ") " . $mysqli->error;
}

/* Prepared statement, stage 2: bind and execute */
if (!$stmt->bind_param("i", $id)) {
    echo "Binding parameters failed: (" . $stmt->errno . ") " . $stmt->error;
}
if (!$stmt->bind_param("s", $json)) {
    echo "Binding parameters failed: (" . $stmt->errno . ") " . $stmt->error;
}
if (!$stmt->bind_param("s", date('Y-m-d H:i:s'))) {
    echo "Binding parameters failed: (" . $stmt->errno . ") " . $stmt->error;
}

if (!$stmt->execute()) {
    echo "Execute failed: (" . $stmt->errno . ") " . $stmt->error;
}

编辑

此外,@JoshJ 关于您的值为 JSON 字符串的说法是正确的...重新编码 Json 字符串将双重转义所有内容。如果这不是您的预期用途(即以字符串形式检索值),那么您实际上应该尝试使用以下方法将每个字符串解码为关联数组:

foreach ($items as $key => $item) {
    $items[$key] = json_decode($item, true);
}

这将为您提供 $items 值为:

[
    0 => [
        "id" => "1",
        "qty" => "1",
        "price" => :"12.51"
    ],
    1 => [
        "id" => "2",
        "qty" => "2",
        "price" => "25.02"
    ]
]

当然还有其他选项可以将数字字符串视为输出中的数字,您可能还想研究一下......

参见:http://php.net/manual/en/function.json-decode.php

编辑2 在 Symfony 中,您可能需要使用 PDO bindParam() 函数语法。

$sql = 'INSERT INTO vals (id, items, timestamp) VALUES (:id, :items, :datetime)';
$stmt = $pdoconnection->prepare($sql);
$stmt->bindParam(':id', $id);
etc...

参见:http://php.net/manual/en/pdostatement.bindparam.phphttp://php.net/manual/en/class.pdostatement.php

关于PHP json_encode() 在数组元素周围添加额外的双引号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33946738/

相关文章:

php - "It is not safe to rely on the system' s 时区设置”

php - MySQL - 从单独的查询中减去

MySQL 组合/连接/多选查询

php - 自运行 php 脚本?

php - 函数的多次返回

javascript - PHP 指向错误 404 不起作用

php - 使用简单项目的 SKU/ID 以编程方式在 Magento 中添加 bundle 产品

java - JSP GlassFish 错误

mysql - 是否可以在 MYSQL 上对每个 UNION 进行分组?

Mysql Count with DAYOFWEEK AND BETWEEN 不能一起工作