1

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.

user2232681
  • 839
  • 4
  • 16
  • 33

2 Answers2

9

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) . "'";
Rizier123
  • 58,877
  • 16
  • 101
  • 156
Jordan
  • 1,433
  • 8
  • 14
6

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);
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • Hello Barmar , kindly, this looks making things pretty automatic. Does this work if the rows are many? Or some cycle is needed? – Robert Jul 26 '17 at 16:37
  • @Robert If you try to use multiple `VALUES` lists in a single insert, make sure you don't exceed `max_allowed_packet`. – Barmar Jul 27 '17 at 20:21
  • Hi Barmar, thank you for the reply. Well, the rows will be not more than 20 or maximum 30. The poin is that I'm newbie. I have created one question here on stackoverflow https://stackoverflow.com/questions/45349503/php-mysql-insert-multimensional-associative-array-building-query-from-array-keys , can you kindly help me there? Thank you for any. – Robert Jul 28 '17 at 04:39
  • Or this solution applies exactly as in my question? If yes, just paste it there an I'll also provide to mark it as accepted (obviously) :-). Thank you for helping this noob ;-) – Robert Jul 28 '17 at 04:56
  • Ouch! Perfect, thank you for the duplicate question links. – Robert Jul 28 '17 at 05:31