Page 1 of 1

foreach $_POST as $key => $value

Posted: Mon Feb 13, 2012 4:12 pm
by lovelf

Code: Select all

<?php
foreach($_POST as $key => $value){
echo $key.' '.$value.'<br>';
INSERT INTO table_name (column1, column2, column3,...)
VALUES (value1, value2, value3,...) 
}
?>
Allright, I want to insert into table_name the columns which are the $key but it would allow me to insert a record at a time with that code, and insert the values which are $value but the same happens.

it would be INSERT INTO table_name($key, $key2, $key3,etc)
VALUES($value,$value2,$value3,etc)

Do I need more arrays than the $_POST? How to create them and set some code in action.

Thanks

Re: foreach $_POST as $key => $value

Posted: Mon Feb 13, 2012 4:27 pm
by Celauran
Do you mean something like this?

Code: Select all

if (!empty($_POST))
{
    $columns = array();
    $values  = array();

    foreach ($_POST as $key => $value)
    {
        $columns[] = $key;
        $values[]  = "'{$value}'";
    }

    $query = "INSERT INTO table_name (" . implode(", ", $columns) . ") VALUES (" . implode(", ", $values) . ")";
}