关于php:implode()数组,将记录插入到MySQL数据库中

implode() array to insert record into mySql database

我在PHP数组中只有一行,我想通过将键和值内插到字符串中并在我的Insert语句中使用这些字符串来将该行插入mySQL数据库,如下所示:

1
2
3
4
5
6
7
8
$fields = implode(",", array_keys($_POST));
$newdata = implode(",", $_POST);

$query = (
"INSERT INTO Food_entered ($fields)
VALUES ('$newdata')"
);

$result = mysqli_query($dbc, $query);

我能够创建字符串,并且它们似乎格式正确,但是未插入行。 似乎是一种简单的方法,但不确定我缺少什么。


正如@Barmar指出的那样,问题在于您的引号位于变量的外部。

我认为这可能比Barmar发布的方法更容易遵循/更干净的解决方法:

1
$newdata ="'" . implode("','", $_POST) ."'";


您需要引用每个值,而不是整个值列表:

1
2
3
4
5
6
7
8
9
10
$fields = implode(",", array_keys($_POST));
$newdata = implode(",", array_map(function($x) use ($dbc) {
    return"'" . $dbc->real_escape_string($x) ."'";
}, $_POST));

$query = (
"INSERT INTO Food_entered ($fields)
VALUES ($newdata)"
);

$result = mysqli_query($dbc, $query);