带有LIKE子句的PHP参数化mysql语句返回命令不同步

时间:2017-11-26 20:31:19

标签: php mysql pdo

我正在尝试使用带有php和mysql的参数化查询的LIKE子句。每次我尝试,我都会遇到不同的错误。

我已尝试实施hereherehere的解决方案。每一个都会抛出不同的错误,所以我担心这个问题出现在我所缺失的问题中。如果我在execute函数中尝试使用数组,则会出现Command不同步错误。当我尝试绑定值或参数时,我得到了一个无法绑定字符串错误。

我因为我失踪而感到茫然。

感谢您的帮助!

 <? 
    $access = 3;
    $dbConnect = true;
    require "../scripts/php/scriptSecurity.php";

    // Partial name given by user.
    $namePart = $_GET["namePart"];

    // Deal with name parts. last, first middle or first middle last, or first last
    if (strpos($namePart, ',') !== false){
        $arr_name = explode(",", $namePart);
        $lName = $arr_name[0];
        if (strpos($arr_name[1], " ") !== false){
            $firstName = substr($arr_name[1], 0, strpos($arr_name[1], " ", 1));
            $middleName = substr($arr_name[1], strpos($arr_name[1], " ", 1));
        }
    }
    elseif (strpos($namePart, " ") !== false){
        $arr_name = explode(" ", $namePart);
        if (sizeOf($arr_name) == 3) {       
            $fName = $arr_name[0];
            $lName = $arr_name[3];
            $mName = $arr_name[2];
        }
        elseif (sizeOf(arr_name) == 2) {
            $fName = $arr_name[0];
            $lName = $arr_name[1];
            $mName = $arr_name[1];
        }
        else {
            $fName = $namePart;
            $mName = $namePart;
            $lName = $namePart;
        }
    }
    else {
        $fName = $namePart;
        $lName = $namePart;
        $mName = $namePart;
    }
    // Get rid of extra spaces.
    $fName = str_replace(" ", "", $fName);
    $lName = str_replace(" ", "", $lName);
    $mName = str_replace(" ", "", $mName);
    // build query
    $query = "SELECT LastName, FirstName, MiddleName, StudentId, Gender, Grade, GradYear FROM students WHERE LastName LIKE ? OR FirstName LIKE ? OR MiddleName LIKE ? ORDER BY LastName, FirstName LIMIT 20";
    $stmt = $connect->prepare($query);
    // execute
    $stmt->execute(array('%'.$lName.'%', '%'.$fName.'%', '%'.$mName.'%'));
    $result = $stmt->get_result();
    // post results
    if (!$result) {
        echo $connect->error;
        echo "No Results";
    }
    else {
        echo "Results";
        while ($row = $result->fetch_assoc()){
            ?>
                <div><? echo $row["LastName"] . ", " . $row["FirstName"] . "(" . $row["StudentId"] . ")"?> </div>
            <?php 
        }
    }
?>

1 个答案:

答案 0 :(得分:0)

你以错误的方式使用wildchar传递param中的字符串你可以使用最简单的方法用concat管理wildchar并将pure var指定为param

  $query = "SELECT LastName, FirstName, MiddleName, StudentId, Gender, Grade, GradYear 
  FROM students 
  WHERE LastName LIKE concat('%',?, '%') 
  OR FirstName LIKE concat('%',?, '%')
  OR MiddleName LIKE concat('%',?, '%')
  ORDER BY LastName, FirstName 
  LIMIT 20";
  $stmt = $connect->prepare($query);
  // execute
  $stmt->execute(array($lName, $fName, $mName));