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.

2
  • What are you getting back from the $result? Commented Jul 19, 2013 at 23:44
  • Hmmm....Column count doesn't match value count at row 1. Thought I checked that. Not sure why when I there are an equal number of keys and values. Commented Jul 19, 2013 at 23:52

2 Answers 2

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) . "'";
Sign up to request clarification or add additional context in comments.

1 Comment

I see that. I just needed to remove the double quote before implode and your suggestion worked fine.
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);

5 Comments

Hello Barmar , kindly, this looks making things pretty automatic. Does this work if the rows are many? Or some cycle is needed?
@Robert If you try to use multiple VALUES lists in a single insert, make sure you don't exceed max_allowed_packet.
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 stackoverflow.com/questions/45349503/… , can you kindly help me there? Thank you for any.
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 ;-)
Ouch! Perfect, thank you for the duplicate question links.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.