Reputation: 43
I have this line in my registration page.
if (device_id_exists($_POST['device_id']) == true) {
$errors[] = 'Sorry the Serial Number \'' . htmlentities($_POST['device_id']) . '\' does not exist.';
}
I have this in my function page.
function device_id_exists($device_id) {
$device_id = sanitize($device_id);
$query = mysql_query("SELECT COUNT(`numbers`) FROM `devicenumbers` WHERE `numbers` = '$numbers'");
return (mysql_result($query, 0) == 0) ? true : false;
If I run this query SELECT COUNT(
numbers) FROM
devicenumbersWHERE
numbers= '1234567890'
(a valid number) it will return 1 = match found right? If I put a bogus number it returns a '0'.
What is happening is when there is a valid number it still returns the error the number doesn't exist. If I change it to the result to == 1 it will submit any number? Im a newbie to DB calls any help appreciated. I hope I provided enough info.
Upvotes: 1
Views: 150
Reputation: 8572
Looks like you're calling the incorrect variable. Within the device_id_exists() function, you're accepting a variable named $device_id
. However when you're performing the query, you're calling what appears to be an undefined variable: $numbers
. I suspect $numbers
should be renamed to $device_id
.
I see your $device_id
comes from a form post. I'd HIGHLY recommend you escape the variable, using mysql_real_escape_string()
to ensure you are protected against SQL injection. Please note that sanitize()
does NOT protect against SQL injection!
On one additional note, I'd recommend utilizng mysql_num_rows()
rather than mysql_result()
because mysql_result()
actually asks the database server to return an actual result when all you really care about is whether the entry exists or not, not it's actual value.
function device_id_exists($device_id) {
$device_id = sanitize($device_id);
$device_id = mysql_real_escape_string($device_id);
$query = mysql_query("SELECT COUNT(`numbers`) FROM `devicenumbers` WHERE `numbers` = '$device_id'");
return mysql_num_rows($query) ? True : False;
}
Upvotes: 2
Reputation: 405
I had a similar problem with mysql result set , It returns nums_rows == 1 even when there are no records (while using max() inside select query - In your case you have used count())... Instead of checking mysqlquery to 0, check it whether the result set empty (That's how i solved my problem).. eg. if(!empty(mysql_result($query))) ? true : false;
Upvotes: 0