Is there anyway to do this faster and with less code? Intermediate
class Useradd 开发者_如何学运维{
function insert_user_into_database($user_firstname, $user_lastname, $user_email) {
$sql = "INSERT INTO user (user_firstname, user_lastname, user_email)
VALUES ('$user_firstname', '$user_lastname', '$user_email')";
$q = mysql_query($sql);
}
}
$user_firstname = mysql_real_escape_string($_POST['firstname']);
$user_lastname = mysql_real_escape_string($_POST['lastname']);
$user_email = mysql_real_escape_string($_POST['email']);
$useradd = new Useradd;
$useradd->insert_user_into_database($user_firstname, $user_lastname, $user_email);
Faster code and reduced lines is not something you should be concerned about when looking at the code above.
- Not proper OOP design: A class isn't just a wrapper for a function
- The sanitization should be internalized to the class
- mysql_real_escape_string isn't always the right choice to sanitize inputs
- Your method does nothing with the result, that's never good.
So, really, the best answer is to say, "You need to add a lot to that code."
If someone's telling you the best programs are the shortest, they're an idiot. If someone tells you the longest programs are the best, they're an idiot also. The best programming does exactly what it needs to do, and exactly what should happen. Trying to put everything into one-liners or make it run as fast as it can leads to a lot of problems, especially when you need to maintain that code a month later.
You could make your insert_user_into_database
function static, so that you don't have to create an instance of the Useradd
object just to insert a new user:
class Useradd {
static function insert_user_into_database($user_firstname, $user_lastname, $user_email) {
...
}
}
Then:
Useradd::insert_user_into_database($user_firstname, $user_lastname, $user_email);
Is the class necessary? There is no advantage in this case to declaring a class, instantiating it, and then calling a class method; just create a normal function and execute that.
精彩评论