In your case, you can construct the WHERE
clause such that it does not need dynamic parameters. Use boolean AND
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.
$sql = "
SELECT ProductName, ProductId
FROM Product
WHERE 1=1
AND ((? <> '' AND ProdukName LIKE ?) OR ProdukName LIKE '%')
AND ((? <> '' AND Produkcode LIKE ?) OR Produkcode LIKE '%')
";
// Then bind each variable *twice*
if($stmt = $mysqli->prepare($sql)){
$stmt->bind_param ('ssss', $produkname, $produkname, $produkcode, $produkcode)
$stmt->execute();
//else code
}
How this works:
AND ((? <> '' AND ProdukName LIKE ?) OR ProdukName LIKE '%')
This creates a condition where the first ?
(supplied by a bound variable) if <> ''
will cause the AND ProdukName Like ?
to be also evaluated. If the variable was empty, on the othre hand, the other side of this expression OR ProdukName LIKE '%'
will be evaluated instead. That matches any ProdukName
value so essentially the entire expression is canceled out.