0

I am needing away to insert data to a database based on an auto generated list from a form.

So I have this that lists out the key and value, but I need to create an array that I can then use a $sql insert to database.

foreach ($_POST as $key => $value) {
        if($value != "") {
            print $key.": ".$value . "<br>";
        }
}

So then I have this for $sql insert

$sql = "INSERT INTO FDPU ($key) VALUES ('$value')";
if ($conn->query($sql) === TRUE) {
echo $key.'='.$value.'New record created successfully'.'<br />';
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
4
  • so put that query code inside your loop. you don't have to build an array, because $_POST is already an array... and note that you're almost certainly vulnerable to sql injection attacks Commented Jun 26, 2015 at 14:52
  • I am guessing that you want the SQL to look like INSERT INTO FDPU ([key1], [key2]...) VALUES ('[value1]', '[value2]'...)? Commented Jun 26, 2015 at 14:54
  • If I put the query code inside the loop it creates a record/row for every value, I need the values to be inserted within the same row. And I will tackle the sql injection attacks. Commented Jun 26, 2015 at 14:54
  • Yes @Anders that is the concept I am trying to achieve. Commented Jun 26, 2015 at 14:55

1 Answer 1

1

Not tested, but something like this should do it:

$keys = array();
$values = array();

foreach ($_POST as $key => $value) {
        if($value != "") {
            $keys[] = $key;
            $values[] = "'" . $value . "'";
        }
}

$sql = "INSERT INTO FDPU (" . implode(',', $keys) . ") VALUES (" . implode(',', $values) . ")";

It stores the keys and values of the variables that are not empty, and then put them together using the very handy function implode.

Sign up to request clarification or add additional context in comments.

1 Comment

That works perfect, thank you. I knew i was close with it, just couldn't get that last part. I have the main form page generated from the columns in database which is automated, and wanted this part to be automated as well. Seriously, thank you so much.

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.