【问题标题】:cakephp findbyid not working correctcakephp findbyid 无法正常工作
【发布时间】:2014-05-07 18:06:38
【问题描述】:

我正在开发一个网络服务(cakephp 2.4.7),我在用户模型上使用 findById 方法。

我拥有的是:

    $user = $this->User->findById($userid);
    if (!$user) {
        throw new NotFoundException(__('Invalid User'));
    }

问题是,如果$userid == 2 我得到了 ID 为 2 的用户。到目前为止一切都很好。但是如果(例如)$userid == 2as 我也得到了 id 为2 的用户。

我认为问题在于,$userid 是一个字符串,而2as 变成了2

我该如何解决这个问题?

【问题讨论】:

  • 我不确定,试试===
  • 使用 is_int() 验证 $userid in2.php.net/manual/en/function.is-int.php
  • 问题是 2 也是一个字符串,如果我检查 is_int($userid) 结果总是假的。
  • 将其称为“功能”就完成了 :-) 更严重的是,is_int() 检查类型,is_numeric() 接受十进制数字,因此它们不适合这项工作。但是您可以使用像这样的简单正则表达式 stackoverflow.com/questions/4100022/php-validate-integer
  • 问题是我有一个功能,我通过比较$this->Auth->User('id')$userid 来检查用户是否访问了他自己的个人资料,这会返回false..暂时我用$userid = intval($userid); 解决了这个问题控制器中每个动作的顶部。

标签: php cakephp cakephp-2.4.7


【解决方案1】:

这就是数据库的工作原理

您似乎很可能正在使用 MySQL,而您所描述的只是它的工作原理:

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)

通过这样的输入,数据库将在执行查询之前将值转换为整数。

如果您想阻止您的应用程序将这两个用户输入视为相同 - 您需要验证用户输入并在使用之前确保它是数字。

【讨论】:

    猜你喜欢
    • 2013-05-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多