前兩天一直寫一個基於thinkphp的東西,遇到從mysql數據庫里select數據,where條件一直出現問題的情況。直接上代碼:
$history = M('history');
$suerId = $_SESSION['user_id'];
$rs=$histroy->where('history_user_id = $userId')->select();
上面代碼$rs一直返回false。不得其解。
后來gettype($userId) 返回string
想是不是histroy_user_id匹配的是數字。然后把$userId改為數字4,可以取出數據。
然后就把$userId改為(int)$userId,發現不管用,還是取不出數據。
后來就看了看thinkphp的手冊,手冊上也沒有做解釋,但看到可以用數組的形式來寫條件。隨后就改為下面的形式可以select出數據。
$history = M('history');
$where['user_id'] = $_SESSION['user_id'];
$histroy->where($where)->select();
至於到底應該用上面類型的數據跟字段history_user_id來匹配至今不知。還請大神們拍磚,指導?
根據大神們的指導:發現一下方法都是可行的。
- 數組存放條件,如上面。$where['history_user_id']=$userId; $history->where($where)->select();此處要注意where數組的索引要與判斷的數據庫表的字段保持一致。
- $history->where("history_user_id = $userId")->select(),where條件有變量的時候要用雙引號,單引號里的變量不解析。
- $history->where('history_user_id = '.$userId)->select() 也是可以的
更新於2013.11.04