1

I have a users table(MySQL) and the unique id is an AI field(user_id). I have a function to get the name of a user from the database, and the only parameter passed to it is the user_id. Lets say the name of the user with user_id=8 is "Jony Bravo". Here's my function:

function getName($user_id)
{
$sql="SELECT name FROM users WHERE user_id='$user_id'";
$result=mysql_query($sql) or die(mysql_error());
$row=mysql_fetch_assoc($result);
return ($row['name']);
}

both the function calls below return the same value: "Jony Bravo"!

echo getName(8);
echo getName('8k');

It's not just k, any characters after the numeral seem to be ignored. Kindly help.

gthuo
  • 2,376
  • 5
  • 23
  • 30
  • Indeed, MySQL casts types very closely to how PHP does. – deceze Dec 18 '12 at 09:31
  • What's the actual problem? – N.B. Dec 18 '12 at 09:34
  • you people reply so fast. I appreciate. @deceze, so MySQL will typecast a string starting with an int to an int? – gthuo Dec 18 '12 at 09:41
  • @N.B., it's just that it's causing some errors which are not so interesting. Also, I'm curious and want to sharpen my expertise. – gthuo Dec 18 '12 at 09:42
  • @GThuo If you want to sharpen your expertise, it's *really* important to not trust any data given by any user: http://stackoverflow.com/questions/60174/how-to-prevent-sql-injection – h2ooooooo Dec 18 '12 at 09:46

2 Answers2

0

The ID I imagine is Integer. If so when the string '8k' is converted to int all the non numerical charters are ignored and you are left with 8. Pass '2k' to the function and if you get the second record that means I'm correct. But this is bad practise you should not pass strings to function that must accept only integers.

DimDqkov
  • 155
  • 1
  • 3
  • 10
0

If you try this:

SELECT 8='8k'

you can see that it returns true! That's because 8 is a int, and 8k is a string, and 8k converted to int becomes 8.

This returns false instead:

SELECT CAST(8 as char)='8k'

So you have to write your query like this:

SELECT name FROM users WHERE CAST(user_id as char)='$user_id'

Or you have to make sure that $user_id is numeric, and remove ':

SELECT name FROM users WHERE user_id=$user_id
fthiella
  • 48,073
  • 15
  • 90
  • 106