mysqli参数化使用数组的查询

时间:2013-10-06 17:58:36

标签: php mysql sql arrays mysqli

如何使用带有sql查询的数组然后循环遍历 结果

这是我所拥有的,但我不确定应该如何使用 在我的查询中内含变量

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<titleard Log</title>
<link rel="stylesheet" type="text/css" media="all" href="jsDatePick_ltr.min.css" />
<script type="text/javascript" src="jsDatePick.min.1.3.js"></script>
<script type="text/javascript">
 window.onload = function() { new JsDatePick({ useMode:2, target:"inputField", dateFormat:"%d-%m-%Y" }); new          JsDatePick({ useMode:2, target:"inputField2", dateFormat:"%d-%m-%Y" }); }; 
</script>
</head>
<body>   

 <form action="#" method="post"> 
 <input type="checkbox" name="driver[]" value="Julia">Julia 
 <input type="checkbox" name="driver[]" value="Pete">Pete From 
 <input type="text" name="date1" size="12" id="inputField" /> To 
 <input type="text" name="date2" size="12" id="inputField2" /> 
 <input type="submit" value="Submit" name="submit"/> 
 </form> 

<?php 
if(isset($_POST['submit']) && ($_POST['submit'] == "Submit")) 
{ 
$date1 = $_POST['date1'];
$date2 = $_POST['date2'];
$date1 = date("Ymd", strtotime($date1));
$date2 = date("Ymd", strtotime($date2));
$drivers = "'".implode("','",$_POST['driver'])."'";
}

$mysqli = new mysqli('' );

if($mysqli->connect_error)
echo {
die("$mysqli->connect_errno: $mysqli->connect
_error");
}

$query = "SELECT * FROM wizardlog WHERE driver IN (?) AND date between ? and ? ";

$stmt = $mysqli->stmt_init();
if(!$stmt->prepare($query))
{
print "Failed to prepare statement\n";
}
else
{
              $stmt->bind_param("sss", $drivers, $date1, $date2);
              $stmt->execute();
            $result = $stmt->get_result();
            while ($row = $result->fetch_array(MYSQLI_ASSOC))
        {
            foreach($rows as $row) 
        { 
        $id = $row['id'];
        $driver = $row['driver'];
        $date = date("d/m/y", strtotime($date));
         $time = $row['time'];
          $time = substr($time, 0, 5);
        $fname = $row['fname'];
        $lname = $row['lname'];
        $town = $row['town'];

任何帮助都会非常感激!

1 个答案:

答案 0 :(得分:0)

参数只能代替一个标量值。不是值列表。

要参数化列表,您需要的参数数量等于列表中元素的数量。

但是mysqli使得bind_param()使用可变数量的元素非常困难。原因是bind_param()需要你通过引用传递参数,所以你不能只传递一个数组;你需要传递一系列的引用。这是皇家PITA。

使用PDO要容易得多,因为这样你就可以简单地将一组值传递给PDOStatement::execute()方法。