PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!
Hello everyone, I would like to gather all of the post variables from a certain form, and then put all of these variables into the database (after security to disallow injection, of course). So, I have the following code:
<? //I have omitted the security code below for brevity
foreach($_POST as $postname => $value) {
$sql = mysql_query('INSERT INTO `table` (`'.$postname.'`) VALUES ("'.$value.'")');
};
?>
Understandably, the result is that each field updated with value "$value" is on a new row! I would like for them to be in the same row. Any thoughts would be much appreciated.
Obviously, you have a foreach , if your $_POST array have 10 values, you will run on foreach 10 times , so you will create 10 differents rows with $value.
I guess the point is that the OP should build 1 query, instead of building a new query for each item...Since you probably need to append both the column name and the value per item, you'll probably have two subparts:
mysql_query('INSERT INTO `table` (`form_data`) VALUES ("' . mysql_real_escape_string(serialize($_POST)) . '")');
because it sounds as if he may not know what is going to be posted, and the fields might not exist in the table, and an unexpected field won't cause the query to fail.