条件 URI 段错误 - Codeigniter
我有一个奇怪的问题,所以请耐心等待。我正在使用 _remap 函数在我的 URI 中实现 example.com/user/username 协议,并且使用以下代码:
function _remap()
{
//URI Segment I am retrieving (this part works for me)
$profile_name = $this->uri->segment(2,0);
// Query the DB where user_name (column in DB) == $profile_name
$query = $this->db->get_where('users', array('user_name' => $profile_name));
// Load user data when URI segment is retrieved, load page
foreach($query->result() as $row){
$this->load->view('user_view', $data);
}
}
所以我的问题是,每当我输入无效的 URI 段时,即在数据库,它只返回一个空白页。我已经尝试了一堆条件语句,但基本上我想要这个算法:
if $profile_name = FOUND (in DB)
display page
else
redirect to error page
就像我说的,我能够让它接受有效的数据库用户名,但如果是无效的,它只会显示一张空白页。我认为这是因为我在segment(2,0)函数中包含了0参数。让我知道您的想法...非常感谢大家!
PS 以防万一您想知道为什么我不使用路由功能,我不确定是否可以通过路由完成所有这些工作(无论如何都要根据数据库进行检查)。
I have sort of a weird problem, so bear with me. I'm using the _remap function to implement an example.com/user/username protocol in my URI and I am using the following code:
function _remap()
{
//URI Segment I am retrieving (this part works for me)
$profile_name = $this->uri->segment(2,0);
// Query the DB where user_name (column in DB) == $profile_name
$query = $this->db->get_where('users', array('user_name' => $profile_name));
// Load user data when URI segment is retrieved, load page
foreach($query->result() as $row){
$this->load->view('user_view', $data);
}
}
So my problem is, whenever I type in an INVALID URI segment, i.e. it isn't found in the database, it just returns a blank page. I've tried a bunch of conditional statements, but basically I want this algorithm:
if $profile_name = FOUND (in DB)
display page
else
redirect to error page
Like I said, I am able to get it to accept valid DB user_name, but with an invalid one it'll just display a blank page. I figured it was because I included the 0 argument in segment(2,0) function. Let me know what you think... Thanks so much all!
P.S. Just in case you are wondering why I am not using routing features, I wasn't sure if I could do all this with routing (checking it against the DB anyway).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在 foreach 之前插入:
Just before your foreach, insert this:
您不需要返回 0,因为如果在该位置找不到段,URI 类将返回 FALSE(这与返回 0 一样好)
现在对于您的另一个问题,您可以通过设置自定义路由规则轻松地做到这一点,并且在您路由到的方法中进行用户数据库检查(因此您可以将 _remap 重命名为实际方法,为了讨论起见,我们将其称为 *fetch_user($username)* )
在你的routes.php中,在末尾添加以下内容:
URI 路由参考
你的新 fetch_users功能:
You do not need to return 0, as the URI class will return FALSE if no segment is found at that position (which is as good as returning 0)
Now to your other question, you can easily do this by setting custom routing rules, and doing the user DB check in the method that you route to (so you would rename _remap to an actual method, lets call it *fetch_user($username)* for discussion sake)
In your routes.php, add this at the end:
URI Routing Reference
Your new fetch_users function: