【问题标题】:PHP MySQL select with multiple conditionsPHP MySQL选择多个条件
【发布时间】:2014-02-01 03:08:42
【问题描述】:

我需要使用多个条件从我的数据库中选择行。

现在我做了很多搜索,但找不到任何与我相似的示例。

请不要像鲨鱼一样围绕 SQL 注入和其他东西蜂拥而至,因为我正在学习 PHP 的第二周,而我所做的只会在内部使用。

形式:

<form action="<?php echo $_server['php_self']; ?>" method="post">
    Display results from <input name="from_date" class="src_drop" type="textarea" id="from_date">
    to <input name="to_date" class="src_date" type="textarea" id="to_date"> 
    for <select class="src_drop" name="uniqueid" type="text">

    <?php 
        $sql   = "select * from table_staff";
        $staff = mysqli_query($connection, $sql);
        while($stafflist = mysqli_fetch_array( $staff )) 
        {
            echo '<option value="' . $stafflist['uniqueid'] . '">' . $stafflist['first_name'] . " " . $stafflist['surname'] . '</option>';
        } 
    ?>
    </select>
    <input type="submit" name="submit" class="search" value="">
</form>

选择:

$startDate = date("Y-m-d", strtotime($_POST['from_date']));
$endDate   = date("Y-m-d", strtotime($_POST['to_date']));
$uniqueid  = $_POST['uniqueid'];

$shiftdata = mysqli_query($connection, "SELECT * FROM table_shift 
    INNER JOIN table_staff ON table_shift.uniqueid = table_staff.uniqueid 
         WHERE shift_date BETWEEN '".$startDate."' AND '".$endDate."
           AND table_shift.uniqueid='".$uniqueid."''
      ORDER by shift_date ASC");

我正在尝试显示特定工作人员在特定日期之间的所有轮班。该代码适用于选择日期之间的班次,但在通过uniqueid 添加选择时会中断连接。我尝试了几种不同的(猜测)语法变体,例如和WHERE table_shift.unqiueid... 没有任何运气。

错误:

您的 SQL 语法有错误;检查与您的 MySQL 服务器版本相对应的手册,以在第 1 行的 '15'' ORDER by shift_date ASC' 附近使用正确的语法

【问题讨论】:

  • 唯一id是整数吗?
  • 您是否收到任何错误消息或您的记录没有被选中?
  • 在您的 mysqli_query 语句后添加 or die(mysqli_error($connection) 并检查错误。
  • 我知道你说过不要用关于保护你的查询的讲座蜂拥而至,但从一开始就开始保护你的软件确实是一个好习惯,这样你就永远不会不小心使用你的坏特性你一开始就接受了。
  • 是的,uniqueid 是一个自增整数

标签: php mysql sql


【解决方案1】:

您是否尝试过删除

周围的单引号

..AND table_shift.uniqueid='".$uniqueid."''

这样看起来像

..AND table_shift.uniqueid=".$uniqueid."

这假定您的 uniqueid 字段是整数,而不是字符串。

【讨论】:

  • 我删除了双引号。现在,当我运行查询时,我没有收到任何错误,但查询只是选择日期之间的班次并忽略 uniqueid。
【解决方案2】:

试试这个..(我同意其他人关于使用准备好的声明保护您的数据)

$startDate = date("Y-m-d", strtotime($_POST['from_date']));
$endDate = date("Y-m-d", strtotime($_POST['to_date']));
$uniqueid = $_POST['uniqueid'];
$query = "
SELECT * 
  FROM table_shift x
  JOIN table_staff y
    ON x.uniqueid = y.uniqueid 
 WHERE x.shift_date BETWEEN '$startDate' AND '$endDate'
   AND x.uniqueid = $uniqueid
 ORDER 
    BY x.shift_date ASC;
";

echo $query;
$shiftdata = mysqli_query($connection, $query) or die(mysqli_error($connection));

【讨论】:

  • 你的代码很好用,我不知道我可以使用这样的语法。这也是更“安全”代码的一个例子吗? ($query 是准备好的语句吗?)
  • 没有。但是准备好的语句在其他地方被广泛讨论,面向对象和过程版本都可用。有人认为程序的安全性稍差一些-但我不明白为什么:-(
猜你喜欢
  • 1970-01-01
  • 2013-04-25
  • 2012-03-13
  • 2018-05-06
  • 1970-01-01
  • 1970-01-01
  • 2011-02-26
  • 2011-03-20
  • 1970-01-01
相关资源
最近更新 更多