Search code examples
phpmodel-view-controllerpdosql-like

Fatal error: Uncaught Error: Cannot pass parameter 2 by reference PDO


I am trying a query with LIKE in PDO however I get the following error: Fatal error: Uncaught Error: Cannot pass parameter 2 by reference PDO, in this part of the code. How could I solve it?

function buscador($DB,$categoria_id,$buscado){
    $productos = NULL;
    $sql = "SELECT * from producto WHERE categoria_id = ? LIKE ?";
    $stmt = $DB->prepare($sql);
    //$params = [$categoria_id,':keywords', '%' . $buscado . '%'];
    $stmt->bindParam(1,$categoria_id,PDO::PARAM_STR);
    $stmt->bindParam(2,':keywords', '%' . $buscado . '%',PDO::PARAM_STR);
    $stmt->execute();
    $productos = $stmt->fetchAll();

    return $productos;
}

Solution

  • The second argument to bindParam is passed by reference and therefore cannot be a literal it must be be a variable.

    You also have an error in the Query syntax which I fixed, although I dont know the column name to use, please change that before attempting to use this code.

    function buscador($DB,$categoria_id,$buscado){
        $productos = NULL;
        $sql = "SELECT * from producto WHERE categoria_id = ? AND othercol LIKE ?";
        $stmt = $DB->prepare($sql);
    
        $p2 = '%' . $buscado . '%';
    
        $stmt->bindParam(1,$categoria_id,PDO::PARAM_STR);
        $stmt->bindParam(2,$p2,PDO::PARAM_STR);
        $stmt->execute();
        $productos = $stmt->fetchAll();
    
        return $productos;
    }