After reading this article, it made me wonder if this is actually a good practice for registering new users. Everyone with some PHP studied can see how it works, but I just feel repeating myself if I have to handle all the post data manually. I know it's not 'difficult' nor too long to do at once, but I think it could be handled in a better way on the long run if you implemented it something similar to this code. For example, to add a single field more you have to change a lot of code, doing copy/paste in the article, but here it's only one field more in the array $ValidFields
. What do you think?
function registerUser()
{
// Only place (apart of the mysql table, obviously) to add new fields of all the script.
$ValidFields = array ("name","lastname","email","password");
$tablename="users"; // If oop, this could be done in the __construct()
foreach ($_POST as $key => $value)
if(in_array($key,$ValidFields))
{
$key=mysql_real_escape_string($key);
if ($key=="password") $value=md5($value);
else $value=mysql_real_escape_string($value);
if (!$mysql) // If there is nothing inside
{
$mysql="INSERT INTO ".$tablename." (".$key;
$endmysql=") VALUES ('".$value."'";
}
else
{
$mysql.=", ".$key;
$endmysql.=", '".$value."'";
}
}
$mysql=$mysql.$endmysql.")";
return $mysql;
}
Tested adding this code after the function
$_POST['name']="testname";
$_POST['lastname']="testlastname";
$_POST['email']="teste'mail"; // Checking MySQL injection (;
$_POST['password']="testpassword";
$_POST['CakePHP']="is_a_lie"; // "Hello world" is too mainstream
echo registerUser();
And the returned string is, effectively:
INSERT INTO users (name, lastname, email, password) VALUES ('testname', 'testlastname', 'teste\'mail', 'testpassword')
NOTE! I know that I should not use mysql_, this is only an illustrative script. There are many statements in php5 (PDO, MYSQLi, etc) that everyone should use. I'm focusing on scalability and performance. A similar process could be reproduced for creating the HTML form. Also, it should work similar with a class.
I'm just wondering why, in so many years PHP has been developed and in the 1 year something I've been studying it and searching for information online, I haven't seen any similar and maybe more efficient way of handling POST or GET data.