2013-10-06 36 views
0

如何在SQL查詢中使用數組,然後循環訪問 結果?使用數組的mysqli參數化查詢

這裏是我得到了什麼,但我真的不知道我應該如何在我的查詢中使用 破滅變量

<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']; 

任何幫助將不勝感激!

回答

0

一個參數只能取代單個標量值。不是價值清單。

要參數化一個列表,需要一些等於列表中元素數量的參數。

但是mysqli使得使用bind_param()具有可變數量的元素非常困難。原因是bind_param()需要你通過引用傳遞參數,所以你不能只傳遞一個數組;你需要傳遞一個引用數組。這是一個皇家PITA。

取而代之,使用PDO要容易得多,因爲您可以簡單地將一組數值傳遞給PDOStatement::execute()方法。