I have multiple conditions in WHERE clause which are inputted by user (call them filters). Currently I am processing them this way (don't worry it isn't deployed):
//$by_nickname etc. are filters from $_GET
$conditions = array();
if($by_nickname !="")
{
$conditions[] = " players.lastName LIKE ('%" . $by_nickname . "%')";
}
if($by_steamid !="")
{
$conditions[] = " ids.uniqueId = '$by_steamid'";
}
if($by_ip !="")
{
$conditions[] = " players.lastAddress = '$by_ip'";
}
if($by_msg !="")
{
$conditions[] = " chat.message LIKE ('%" . $by_msg . "%')";
}
if (count($conditions) > 0)
{
$where = implode(' AND ', $conditions);
$query = "SELECT ... WHERE " . $where;
}
else
{
$query = "SELECT ... ";
}
Instead of this I would use
$conditions[] = " ids.uniqueId = ?";
and so on. Now I would also obtain $where
, but with ?
instead of filter values.
Query should be now prepared
$stmt = $mysqli->prepare("SELECT ... WHERE $where");
and parametrized something like this
$stmt->bind_param('ss', $by_nickname, $by_steamid);
But how do I parametrize query if some filters could be empty? Simply, I don't know the bind_param()
method arguments in advance.
I have solved my problem using PDO which has named parameters. So here is my solution, hope it helps somebody.