php - 需要解释 $_GET 的 isset

标签 php mysql get isset

我在这里努力尝试理解 $_GET 的 isset 逻辑测试的逻辑。这实际上是一个练习的答案。

所以是这部分:

if(isset($_GET['status']) && in_array($_GET['status'], $options)){
  $sql .= " WHERE status = ?";
  $execute = array($_GET['status']);
}

如果答案是//inline,我将不胜感激,非常感谢。

1.) 我知道我们正在尝试查看状态是否不为空,但为什么 $options 也要两次?

2.) 为什么 $sql 拆分?为什么不让 $sql 脱离 if 已经有了“WHERE status =?”

PHP 页面的其余部分在这里:

<?php # Exercise solution 1

$employees = '';
$execute = array();
$options = array(0,1);

$db = new PDO('mysql:host=localhost;dbname=eshop;charset=utf8', 'root', '');
$sql = "SELECT firstName,lastName FROM employees";

if(isset($_GET['status']) && in_array($_GET['status'], $options)){
  $sql .= " WHERE status = ?";
  $execute = array($_GET['status']);
}

$query = $db->prepare($sql);
$query->setFetchMode(PDO::FETCH_OBJ);
$query->execute($execute);
$result = $query->fetchAll();

foreach($result as $row){

  $employees .= "{$row->firstName} {$row->lastName}<br/>";

}


?>

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <title>Exercise solution 1</title>
  </head>

  <body>

    <strong>Employees list</strong>&nbsp;&nbsp;
    <a href="1.php">All</a>&nbsp;
    <a href="1.php?status=1">Status Active</a>&nbsp;
    <a href="1.php?status=0">Status Not Active</a>
    <br/><br/>
    <div class="result-list"><?= $employees; ?></div>

  </body>
</html>

最佳答案

我很确定你在这里可能遗漏了一个函数 in_array

in_array($_GET['status'], $options)

$options 将包含 status 可能具有的所有有效值

关于php - 需要解释 $_GET 的 isset,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33700375/

相关文章:

PHP/MYSQL - 通过 as php 变量进行 mysql 查询相关的语法错误

PhpSpec 测试捕获异常

php - 如何防止 DOMDocument 将 < 保存为 &lt

javascript - Laravel 多页面 View 和 session

Django View 从应该发送 POST 的表单接收 GET 请求

php - 检查 php 中的特定输入并在满足所需格式时继续的最佳方法是什么?

PHP:while Loop 不显示数据库问题中的所有结果

php - 无法迁移外键

php - 如何将不同的数据合并到一个表行多列中?

c# - 获取注册表项是否存在,如果存在,则执行此操作,如果不存在,则执行此操作