我正在開發一個使用php的搜索選項。在那裏,我需要使用用戶給定條件的用戶可以搜索做搜索時,用戶給ID,名稱,狀態這三種parameters.below的組合是我的代碼用戶給出多個參數的mysql搜索查詢
if(isset($_POST['search']))
{
echo "<script> document.getElementById('tblsearch').style.display = 'block' </script> ";
$serviceNumber=$_POST['serviceNumber'];
$name=$_POST['name'];
$pendingfrom=$_POST['pendingfrom'];
$status=$_POST['status'];
$datefrom=$_POST['datefrom'];
$dateto=$_POST['dateto'];
$searchkey='serviceNumber';
$mysqli = new mysqli("localhost", "root", "", "user_management");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$query = 'SELECT * FROM user WHERE ';
$where = array();
$values = array();
$types = '';
if (!empty($_POST['serviceNumber'])) {
$where[] = 'serviceNumber = ?';
$values[] = $_POST['serviceNumber'];
$types .= 'i';
}
if (!empty($_POST['name'])) {
$where[] = 'Username = ?';
$values[] = $_POST['name'];
$types .= 's';
}
if (!empty($_POST['status'])) {
$where[] = 'status = ?';
$values[] = $_POST['status'];
$types .= 's';
}
$query .= implode(' AND ',$where);
printf("rows inserted: %d\n", $query);
printf("rows inserted: %d\n", $values);
/* prepare statement */
if ($stmt = $mysqli->prepare($query)) {
/* Bind variable for placeholder */
$stmt->bind_param($types,$values);
/* execute statement */
$stmt->execute();
$res = $stmt->get_result();
$row = $res->fetch_assoc();
printf("rows inserted: %d\n", $stmt->num_rows);
/* close statement */
$stmt->close();
}
/* close connection */
$mysqli->close();
below line i was going confused,because $values is an array.i need to pass user given paremeters to this in order to execute.
$stmt->bind_param($types,$values);
so in order to get correct results how do i need to do this.
您可以'foreach' $ values'數組併爲循環的每次迭代綁定適當的參數。 http://php.net/manual/en/pdostatement.bindparam.php –