I'm a 2nd year ICT student. I never did PHP before this year and our instructor gave us the basics and at the end of the semester, gave us a project that would combine what we learned in his course and the databases course. We were to use the classic AMP setup on windows.
Now, our instructor told us to make a profile-site, based on how we made smaller ones before in class.
I don't see the point behind the somewhat weird method of entering the user into the database.
First, we do some PHP formchecking to make sure the entered data is safe and somewhat realistic(for instance, zip-codes over here are 4 numbers, never more and no letters or other symbols).
When everything checks out fine, we do the following:
$sql = new SqlObject(); //from SqlObject.class.php
$newUser = new User(login,passw,mail,...,...,...); //from User.class.php
$sql->addUser($newUser);
The SqlObject class is a class that contains all the SQL commands we need update, insert and generally alter data in the database. We never write SQL in our normal pages. But that's not what I'm confused about. It's the User.class.php file.
This file contains only a constructor and exactly the same amount of fields as needs to be entered into the database. For instance:
<?php
class User {
// members
var $id;
var $name;
var $password;
// constructor
function User($id=-1,$name='',$password='') {
$this->id = $id;
$this->name = $name;
$this->password = $password;
}
}
?>
That's it. The SqlObject.class.php file requires the User.class.php file on the first line.
The function addUser($user)
in the SqlObject.class.php file looks like this:
function addUser($user) {
$insQuery = 'INSERT INTO users(name,password)';
$insQuery.= " VALUES ('".$user->name."', '".$user->password."')";
@mysql_query($insQuery) or showError("user insert failed");
}
Why make such a detour via the User.class.php file? Security reason of some kind?
I'll repeat: It's my first year using PHP and I'm still a student.
EDIT: People are complaining that there is no checks on SQL injection before inserting the data.
At the beginning of this post, I mentioned "formchecking".
The register.php
file does all the escaping and checking of input. This includes several Regex tests, mysql_real_escape_string() and some simpler tests.
Once all tests are passed and all input is escaped, only then will this happen:
$sql = new SqlObject(); //from SqlObject.class.php
$newUser = new User(login,passw,mail,...,...,...); //from User.class.php
$sql->addUser($newUser);
That code is never executed if the input doesn't receive the treatment that I see some people wanting to give it inside the SqlObject.class.php file.
EDIT2: as promised, blog posted: http://webdevhobo.blogspot.com/2009/08/prepared-statements-in-php.html