implode() array to insert record into mySql databa

2019-06-03 03:38发布

I have a single row in a PHP array and I would like to insert that row into mySQL database by imploding the keys and values into a string and using those strings in my Insert statement as follows:

$fields = implode(",", array_keys($_POST));
$newdata = implode(",", $_POST);

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

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

I am able to create the strings, and they appear to be in proper form ,however the row is not being inserted. Seems like a simple approach but not sure what I'm missing.

2条回答
SAY GOODBYE
2楼-- · 2019-06-03 04:10

As @Barmar has pointed out, the problem is your quotes are on the outside of your variable.

I think this may be an easier to follow/cleaner way of fixing this however than the method Barmar posted:

$newdata = "'" . implode("','", $_POST) . "'";
查看更多
做自己的国王
3楼-- · 2019-06-03 04:10

You need to quote each value, not the entire list of values:

$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);
查看更多
登录 后发表回答