Home » Php » function – php Warning: mysqli_stmt::bind_param(): Number of variables doesn't match number of parameters in prepared statement Universal Select

function – php Warning: mysqli_stmt::bind_param(): Number of variables doesn't match number of parameters in prepared statement Universal Select

Posted by: admin February 25, 2020 Leave a comment

Questions:

I’m trying to make a universal function that deals with all my select statements. However I keep getting this warning:
Warning: mysqli_stmt::bind_param(): Number of variables doesn’t match number of parameters in prepared statement

    function selects($table, $columns, $where, $sorting){
        $conn = connectDB();

        $sql = "SELECT $columns FROM $table ";

        $params = array();
        if ($where != "0"){
            $sql = $sql . "WHERE ";

            $conditions = explode(" AND ", $where); // seperates the different conditions

            foreach ($conditions as $i){
                //echo "testen";
                //if i contains LIKE 
                if (strpos($i, 'LIKE') !== false) {
                    //echo 'true';
                    $condition = explode("LIKE", $i);
                    $sql .= $condition[0] . " LIKE '%?%' "; //this gives the error

                    //echo $condition[0];

                    array_push($params, $condition[1]); //adds parameter to param array
                } else { //if i contains " = "
                    $condition = explode(" = ", $i); //split condition
                    $sql .= $condition[0] . " = ? "; //gives second error

                    if(is_numeric($condition[1])){
                        $param = intval($condition[1]);

                        array_push($params, $param);
                    }


                    array_push($params, $condition[1]);
                }
            }
        }

        if($sorting != "0"){
            $sql .= $sorting; //ORDER BY
        }

        echo $sql; //just to double check my statements

        $stmt = $conn->prepare($sql);

        if(!$stmt){
            die('mysqli error: '.mysqli_error($conn));
        }

        //$stmt->bind_param($types, $params);
        bindVariables($stmt, $params); 
        $stmt->execute();
        mysqli_stmt_store_result ($stmt);

        if ($result = $conn -> query($sql)){
            $conn -> close();
            return $result;
        } else {
            echo "error" .$conn->error;
            $conn -> close();
        }
    }

I also use the function bindVariables() in my function for inserts and here it cause no errors or warnings.

I tried removing the quotation marks in the like, but allas to no avail, I’ve also tried adding the %signs to the variable and only leaving the like in the query but this gives me a mySQL syntax error.

It is probably a simple oversight as I’m new to php

How to&Answers: