动态mysql查询准备好了

时间:2016-04-27 12:35:10

标签: php mysql

我在PHP中创建动态查询。

#$id = $_POST[id];
#$field1 = $_POST[field1];
#$field2 = $_POST[field2];
#$field3 = $_POST[field3];

$id = "id";
$field1 = "222";
$field2 = "787";
$field3 = "4444444";

$whereArr = array();
if($id != "") $whereArr[] = "id = {$id}";
if($field1 != "") $whereArr[] = "field1 = {$field1}";
if($field2 != "") $whereArr[] = "field2 = {$field2}";
if($field3 != "") $whereArr[] = "field3 = {$field3}";

$whereStr = implode(" AND ", $whereArr);

$query = "Select * from assignments WHERE {$whereStr}";
echo $query;

工作正常。

Select * from assignments
WHERE id = id AND field1 = 222 AND field2 = 787 AND field3 = 4444444

我收到了正确的查询,但不再维护mysql。所以,我正在使用这样的预备声明。

$firstname = 'Patrick';
$lastname = 'Allaert';

$query = 'SELECT * FROM users';

$cond = array();
$params = array();

if (!empty($firstname)) {
    $cond[] = "firstname = ?";
    $params[] = $firstname;
}

if (!empty($lastname)) {
    $cond[] = "lastname = ?";
    $params[] = $lastname;
}

if (count($cond)) {
    $query .= ' WHERE ' . implode(' AND ', $cond);
}
echo $query;

问题是如何绑定参数。

$stmt->bind_param("sss", $firstname, $lastname, $email);

感谢您的建议。

2 个答案:

答案 0 :(得分:1)

您可以将数组传递给execute,它将绑定该数组的值。

$firstname = 'Patrick';
$lastname = 'Allaert';

$query = 'SELECT * FROM users';

$cond = array();
$params = array();

if (!empty($firstname)) {
    $cond[] = "firstname = ?";
    $params[] = $firstname;
}

if (!empty($lastname)) {
    $cond[] = "lastname = ?";
    $params[] = $lastname;
}

if (count($cond)) {
    $query .= ' WHERE ' . implode(' AND ', $cond);
}
$stmt = $pdo->prepare($query);
$stmt->execute($params);

您可以在手册上看到这种方法,例如#3。 http://php.net/manual/en/pdo.prepared-statements.php

Mysqli方法:

$firstname = 'Patrick';
$lastname = 'Allaert';
$query = 'SELECT * FROM users';
$cond = array();
$params = array();
if (!empty($firstname)) {
    $cond[] = "firstname = ?";
    $params[] = $firstname;
}
if (!empty($lastname)) {
    $cond[] = "lastname = ?";
    $params[] = $lastname;
}
if (count($cond)) {
    $query .= ' WHERE ' . implode(' AND ', $cond);
}
$stmt = $mysqli->prepare($query);
if(!empty($params)) {
    $n = count($params);
    $a_params[] = & str_repeat('s', $n);
    for($i = 0; $i < $n; $i++) {
      $a_params[] = & $params[$i];
    }
    call_user_func_array(array($stmt, 'bind_param'), $a_params);
}
$stmt->execute();
$res = $stmt->get_result();
while($row = $res->fetch_array(MYSQLI_ASSOC)) {
    print_r($row);
}

答案 1 :(得分:0)

脚本中不需要数组

您可以使用如下脚本:

$where = " 1=1";
if($id != "") $where .= " and id = $id ";
if($field1 != "") $where .= " and field1 = '" . $field1 . "' ";
if($field2 != "") $where .= " and field2 = '" . $field2 . "' ";
if($field3 != "") $where .= " and field3 = '" . $field3 . "' ";

$query = "Select * from assignments WHERE $where";
echo $query;