如何使用PHP检查$ _GET ['id']是否已设置并且不为空 [英] How to check whether $_GET['id'] is set and it's not empty using php

查看:275
本文介绍了如何使用PHP检查$ _GET ['id']是否已设置并且不为空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个php代码

if(isset($_GET['id'])) {
    //do something
} else {
    redirect('index.php'); //redirect is a function
}

现在,如果设置了id(例如:index.php?id = 12),则会执行该操作,但是如果未设置id(例如:index.php?id =),这将显示错误,如何解决. .. ??

Now if id is set (ex: index.php?id=12) then the action is performed but if id is not set (ex: index.php?id=) this shows an error, how to overcome this...??

如何确定id是一个整数并且不为空,然后执行特定操作....

How to determine id is an integer and it's not empty and then perform the specific action....

已编辑

谢谢大家的回答,但我仍然遇到该错误...

Thank you all for your answers but i am still getting that error...

if(isset($_GET['id'])) { // I implemented all these codes but still....
    $user= User::find_by_id($_GET['id']);
   // Database Classes Fetches user info from database
}
else {
    redirect('index.php'); //redirect function
}

如果id为1或大于1,那么脚本将完美执行. (index.php?id = 1)

If the id is 1 or greater than 1 then the script executes perfectly. ( index.php?id=1 )

但是id我将id设置为注意我得到一个错误,即index.php?id =

But id i set id as noting i get an error i..e index.php?id=

代码应自动将用户重定向到index.php页面,而不显示错误.....

The code should automatically redirect user to the index.php page instead of showing an error.....

错误:数据库查询失败:您的SQL语法有错误;查看与您的MySQL服务器版本相对应的手册以获取正确的语法,以在第1行的"LIMIT 1"附近使用

ERROR : Database query failed: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'LIMIT 1' at line 1

推荐答案

您应同时检查set-status和内容:

You should check both the set-status and the content:

if ( isset( $_GET['id'] ) && !empty( $_GET['id'] ) )
    // ....

请注意,您应该仅按原样使用值并使用它.您应该确保它仅包含您期望的值.要检查整数,甚至更好地使用整数,请执行以下操作:

Note that you should not use the value simply as it is and work with it. You should make sure that it only contains values you expect. To check for an integer, and even better to work with an integer from that on, do something like that:

$id = ( isset( $_GET['id'] ) && is_numeric( $_GET['id'] ) ) ? intval( $_GET['id'] ) : 0;

if ( $id != 0 )
    // id is an int != 0
else
    redirect('index.php');

这篇关于如何使用PHP检查$ _GET ['id']是否已设置并且不为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆