簡體   English   中英

嘗試讓PHP MYSQL查詢忽略WHERE子句中的空變量

[英]try to have PHP MYSQL query ignore empty variable in WHERE clause

發布變種

$institute = $_POST['institute'];

if (isset($_POST['sections'])) {
    $sections = $_POST['sections'];
}

if (isset($_POST['division'])) {
    $division = $_POST['division'];
}

if (isset($_POST['level'])) {
    $level = $_POST['level'];
}

//check empty var
$where = "WHERE a.institute =?";
$bind = "i";
$prams = "$institute, ";
if (!empty($sections)) {
    $where .= "AND a.section = ?";
    $bind .= "i";
    $prams .= "$sections, ";
}

if (!empty($division)) {
    $where .= "AND a.division =?";
    $bind .= "i";
    $prams .= "$division, ";
}

if (!empty($level)) {
    $where .= "AND a.phase =?";
    $bind .= "i";
    $prams .= "$level";
}

//var_dump($institute, $sections, $division, $level);
var_dump($bind);

//$getSearch = $db->prepare("SELECT * FROM student_basic_info WHERE institute =? AND section = ? AND division =?");
$getSearch = $db->prepare("SELECT
a.*, a.id AS stud_id, b.id, b.ins_name, c.id, c.sec_name, d.id, d.div_name
FROM student_basic_info AS a
JOIN institutes AS b ON (a.institute = b.id)
CROSS JOIN ins_sections AS c ON (a.section = c.id)
CROSS JOIN ins_division AS d ON (a.division = d.id)
$where GROUP BY a.id
");
$studSearch = array();
$getSearch->bind_param("'".$bind."'", $prams);
if ($getSearch->execute()) {
    $results = $getSearch->get_result();
    while ($vStud = mysqli_fetch_array($results)) {
        $studSearch[] = $vStud;
        ?>

得到

(!)致命錯誤:在第59行上的非對象上調用成員函數bind_param()

59行是

$getSearch->bind_param("'".$bind."'", $prams);

解決了Call to a member function bind_param()

現在得到Warning: mysqli_stmt::bind_param(): Number of elements in type definition string doesn't match number of bind variables

看起來$getSearch為空(false)。 檢查您的prepare功能。 成功應該返回true

if ($getSearch = $db->prepare(...)) {
    $getSearch->bind_param(...);
    ...
}
else {
    printf("Errormessage: %s\n", $db->error);
}

您需要在空格中添加AND條件; 現在您的sql無效,並且prepare將失敗:

$where .= " AND a.section = ?";
           ^ here
// etc.

但是,現在您的綁定將失敗,您無法連接值並發送一個長字符串作為第二個參數。 您需要分別綁定每個值。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM