I would like to have a submit code that works with different forms like:
<?php
$type = $_GET['type'];
if(isset($_SESSION['id']))
handle_form();
else
include 'form_'.$type.'.php'; // different fields based upon type
?>
So I was wondering if it was wise to loop through superglobal $_POST writing all keys and values to the database. Something like:
<?php
function handle_form() {
$query = "";
foreach($_POST as $key => $value) {
$query .= mysql_real_escape_string($key)."='".mysql_real_escape_string($value)."' AND ";
}
mysql_query("UPDATE ".$_POST['type']." SET ".substr($query,0,-4)."WHERE `id` = $_SESSION['id']");
}
?>
Or is this a very insecure approach for handling forms and is it better to hardcode all fields in the corresponding ‘form_type.php’?
That is a really bad idea, because then any extra POST fields that don’t correspond to columns would break the query. Your own code uses
$_POST['type']to determine which table you’re updating, which would break as well unless you unset it beforehand.Also, you are not doing any validation on the data that is actually being sent to the DB. Changing your own name/permissions to Admin? Sure. Changing another user’s email to your own? Go ahead. Making your account balance +100,000$? No problem. Mark a product as “price $1”? Yup.
It would be a lot smarter to have some kind of Active Record. If you’re writing a larger application, look into a framework such as Yii or Cake PHP, they come with such functionality built in.
Aside from that: Please stop writing new code with the ancient mysql_* functions. They are no longer maintained and community has begun the deprecation process. Instead you should learn about prepared statements and use either PDO or MySQLi. If you care to learn, here is a quite good PDO-related tutorial.