A MySQL field value starting with a Numeral then followed by characters is treated as Numeric

StackOverflow https://stackoverflow.com/questions/13929862

  •  10-12-2021
  •  | 
  •  

Вопрос

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.

Это было полезно?

Решение

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

Другие советы

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.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top