setting the result of a sql query as a variable inside an if statement in php
Kind of an unclear question but I'm trying to check if a username has been taken or not. The code I have now isn't erroring but it's also not working, when echoing the $username variable I get nothing.
$sql="SELECT people_username FROM people WHERE people_username='{$_POST['username']}'";
//Set the result of the query as $username and if the select fails echo an error messa开发者_如何学Cge
if ($username = !mysql_query($sql,$con)) {
die('Error: ' . mysql_error());
}
else if ($_POST['username'] == $username){
$errors[ ] = 'This username is already in use, please try again...sorry';
}
Is it a syntax error or is my logic wrong?
i would just do
$resource = mysql_query("SELECT people_username FROM people WHERE people_username='".mysql_escape_string($_POST['username'])."'");
if(!$resource) {
die('Error: ' . mysql_error());
} else if(mysql_num_rows($resource) > 0) {
$errors[ ] = 'This username is already in use, please try again...sorry';
} else {
//username is not in use... do whatever else you need to do.
}
If some cheeky user happens to try: '; DROP people; --
as a username, you'd be in big trouble.
You may want to check the following Stack Overflow post for further reading on this topic:
- What is SQL injection?
As for the other problem, the other answers already addressed valid solutions. However, make sure to fix the SQL injection vulnerability first. It is never too early for this.
Your code is wrong.
It should be something like this:
$sql="SELECT people_username FROM people WHERE people_username='".mysql_escape_string($_POST['username'])."'";
//If the select fails echo an error message
if (!($result = mysql_query($sql,$con))) {
die('Error: ' . mysql_error());
}
$data = mysql_fetch_assoc($result);
if ($data == null){
$errors[ ] = 'This username is already in use, please try again...sorry';
}
Notice that for security reasons you need to escape the strings you use in SQL queries.
mysql_query($sql,$con)
returns a resultset (which may be empty)- you are not testing any condition with
if($var = !'value')
, you are just assigning a negated resultset to the variable$username
(what beast that is, I am not sure)
My suggestion: Simplify the code, do not overload lines of code with multiple tasks. 3. List item
精彩评论