I have a php problem when want to bind_param dynamically when I using SELECT
this is my php code
$sql = 'SELECT ProductName, ProductId FROM Product WHERE 1=1'
if($produkname != ''){
$sql .= ' AND ProdukName Like ?';
}
if($produkcode != ''){
$sql .= ' AND Produkcode Like ?';
}
if($stmt = $mysqli->prepare($sql)){
$stmt->bind_param ('ss', $produkname, $produkcode)
$stmt->execute();
//else code
}
I cannot bind_param if one of $produkname
or $produkcode
value is empty
You could also utilize
call_user_func_array
with$stmt->bind_param
to do something like this:In your case, you can construct the
WHERE
clause such that it does not need dynamic parameters. Use booleanAND
conditions to verify that the variable values are<> ''
in the SQL rather than in the PHP, and you can therefore accomplish it using four?
(each variable bound twice) and no dynamic binding.How this works:
This creates a condition where the first
?
(supplied by a bound variable) if<> ''
will cause theAND ProdukName Like ?
to be also evaluated. If the variable was empty, on the othre hand, the other side of this expressionOR ProdukName LIKE '%'
will be evaluated instead. That matches anyProdukName
value so essentially the entire expression is canceled out.You need more conditions: