2015-11-13 56 views
0

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

所以这是这一部分:

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

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

1.)据我所知,我们正试图查看状态是否为空,但为什么两次$选项也是?

2.)为什么是$ sql分裂?为什么不把$ sql带出来,如果已经用“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> 
+2

@FuzzyTree:不,它不。这是一个彻头彻尾的语法错误。我猜它应该是'isset()' –

+0

既然你永远不能确定你从客户端得到了什么数据,你必须首先检查你实际发送的一些数据是否被发送:'if(isset($ _ GET ['状态']))'只有那样你才能真正使用它。 – arkascha

+0

我也有一个错误,那就是为什么即时在这里完全困惑,这是从我们的练习答案。 – erezT

回答

3

我敢肯定你缺少的功能在这里可能in_array

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

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

+0

绝对,修复它。问题依然存在......感谢模糊。 – erezT

+0

@erezT状态根据选项进行验证,以防止用户将状态设置为不允许的状态并选择不允许的数据 – FuzzyTree

3

它使where条款有条件。如果未设置该特定查询参数,则查询仅为SELECT everything。否则它变成SELECT just the one specific record