我试图通过使用GET参数从我的数据库中获取信息。问题是,只要$_GET['archived']
设置为yes
,它仍会执行no
/ !isSet
部分。
if(isSet($_GET['archived']) == "no" || !isSet($_GET['archived'])){
// find out how many rows are in the table
$r = $connection->prepare("
SELECT *
FROM categories
WHERE archived='no'
");
} else if(isSet($_GET['archived']) == "yes"){
// find out how many rows are in the table
$r = $connection->prepare("
SELECT *
FROM categories
WHERE archived='yes'
");
}
答案 0 :(得分:0)
isset
运算符返回true
或false
。所以你必须修改你的代码:
if ((isset($_GET['archived']) && $_GET['archived'] == "no") || !isset($_GET['archived'])) {
// find out how many rows are in the table
$r = $connection->prepare("
SELECT *
FROM categories
WHERE archived='no'
");
} else {
if (isset($_GET['archived']) && $_GET['archived'] == "yes") {
// find out how many rows are in the table
$r = $connection->prepare("
SELECT *
FROM categories
WHERE archived='yes'
");
}
}
答案 1 :(得分:-1)
简单,但有效:)
if (!isset($_GET['archived'] || $_GET['archived'] == 'no')){
// find out how many rows are in the table
$r = $connection->prepare("
SELECT *
FROM categories
WHERE archived='no'
");
}
if ($_GET['archived'] == 'yes') {
$r = $connection->prepare("
SELECT *
FROM categories
WHERE archived='no'
");
}
另外,如果您使用某种框架,请不要直接使用魔法'魔法'变量
答案 2 :(得分:-1)
您正在将isset()函数的结果与字符串" no"进行比较。和"是"。但是,isset将返回布尔值。
删除isset()将导致以下代码块:
if($_GET['archived'] == "no") {
// find out how many rows are in the table
$r = $connection->prepare("
SELECT *
FROM categories
WHERE archived='no'
");
} else if($_GET['archived'] == "yes") {
// find out how many rows are in the table
$r = $connection->prepare("
SELECT *
FROM categories
WHERE archived='yes'
");
}
请注意,您应该始终对从(不受信任的)客户端收到的值(例如$ _GET和$ _POST)进行一些预处理,以降低注入风险。
背景:isset()只会帮助您确定是否已设置值。在非静态类型编程语言中通常需要这种类型的语言函数。
由于您要将isset()函数的结果与字符串进行比较,因此您要求PHP将布尔值与字符串进行比较。
isset — Determine if a variable is set and is not NULL
TL; DR: Isset主要用于检查是否设置了值。不要用它来比较你期望的实际值。