【问题标题】:Query for condition 'ALL' with Variable?使用变量查询条件“ALL”?
【发布时间】:2014-12-24 16:30:16
【问题描述】:

我对 post 变量到 sql 查询感到困惑, 这是我的 report.php 代码示例

<form action="report.php">
<select id="status" name="status">                      
  <option value="MARRIED">married</option>
  <option value="SINGLE">Single</option>
  <option value="ALL">ALL</option>
</select>

<input type="submit" value="Seach">
</form>

<?php

$status= $_GET['status'];

// Create DB connection
$sql = "SELECT * FROM member WHERE status ='$status'";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    // output data of each row
    while($row = $result->fetch_assoc()) {
        echo "<B>id: </B>" . $row["user_id"]. " -- <b>Date Record:</b> " . $row["created"]. " -- <b>Last Seen</b> " . $row["last_seen"]. " -- <b>Status: </b> " 
    }
} else {
    echo "0 results";
}
$conn->close();

?>

如果选择“ALL”条件,如何查询?

【问题讨论】:

    标签: php mysql sql tsql


    【解决方案1】:

    我不知道 PHP,所以这不是确切的代码,但概念应该是这样的

    if( $status == 'ALL' )
        $sql = "SELECT * FROM member";
    else
        $sql = "SELECT * FROM member WHERE status ='$status'";
    

    【讨论】:

    【解决方案2】:

    在这种情况下,将 $status 变量存储在 POST 中是非常明智的,因为 SQL 查询取决于存储在 URL 中的值,因此会暴露给用户。

    另一件事,因为您在这里处理的是遗留代码,所以要额外确保您尽可能多地过滤用户输入和 SQL 查询。使用较旧和过时的功能的问题是,无论您采取何种预防措施,您仍然容易受到 XSS 和 SQL 注入攻击,因此强烈建议您使用 MySQLiPDO(PHP 数据对象)扩展而是因为它们提供了更稳定和高级的功能。

    $status = htmlspecialchars($_GET['status'], ENT_QUOTES);
    $where = '';
    if ($status != 'ALL') {
        $where = 'WHERE status = "$status"';
    }
    
    $sql = mysql_real_escape_string('SELECT * FROM member ' . $where);
    $results = mysql_query($sql);
    

    【讨论】:

    • 嗨 hRdCoder,谢谢,我从没想过,是的,我阅读了很多关于漏洞的信息,但这对我来说没问题,因为这仅适用于我的小型应用程序和私人用途,谢谢hRdCoder.
    • 非常欢迎您,esi0411。希望我的建议对你有所帮助。
    【解决方案3】:

    在 PHP 文件中

    <?php
    
    $status= $_GET['status'];
    
    if($status == 'ALL'){
      $where = '';
    }else{
      $where = 'status = '".$status."' ';
    }
    // Create DB connection
    $sql = "SELECT * FROM member WHERE ".$where." ";
    
    ?>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-05-06
      • 2011-12-12
      • 1970-01-01
      • 1970-01-01
      • 2021-03-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多