i am developing a webservice (cakephp 2.4.7) where i am using the findById method on a user model.
What i have is:
$user = $this->User->findById($userid);
if (!$user) {
throw new NotFoundException(__('Invalid User'));
}
And the problem is, if $userid == 2
i get the user with ID 2. So far so good. But if (for example) $userid == 2as
i also get the user with id 2
.
I think the problem is, that $userid
is a string and 2as
becomes 2
.
How can i solve the issue?
It seems quite likely you're using MySQL, and what you're describing is simply how it works:
mysql> select * from posts where id = 1;
+----+-----------+------------------------+---------------------+----------+
| id | title | body | created | modified |
+----+-----------+------------------------+---------------------+----------+
| 1 | The title | This is the post body. | 2013-08-01 07:34:57 | NULL |
+----+-----------+------------------------+---------------------+----------+
1 row in set (0.00 sec)
mysql> select * from posts where id = "1and this text";
+----+-----------+------------------------+---------------------+----------+
| id | title | body | created | modified |
+----+-----------+------------------------+---------------------+----------+
| 1 | The title | This is the post body. | 2013-08-01 07:34:57 | NULL |
+----+-----------+------------------------+---------------------+----------+
1 row in set, 1 warning (0.00 sec)
With input like that, the database will cast the value to an integer before performing a query.
If you want to prevent your application from treating those two user inputs as the same - you'll need to validate user input and make sure it's numeric before using it.