0

I need to dynamically launch queries based on filters which change over time. Every time the filter is in the string variable $filter. Am I allowed to bind it after WHERE like in the following code? It doesn't seem to work. The resulting query I expect is SELECT NAME FROM PERSONA WHERE GENDER='F'

$filter = "GENDER='F'";
$stmt = mysqli_stmt_init($connection);
mysqli_stmt_prepare($stmt, "SELECT NAME FROM PERSONA WHERE ?");
mysqli_stmt_bind_param($stmt, 's', $filter);
Mureinik
  • 297,002
  • 52
  • 306
  • 350

2 Answers2

0

You can only bind values, not syntactic elements. So either keep the gender condition and just bind the F value:

mysqli_stmt_prepare($stmt, "SELECT NAME FROM PERSONA WHERE GENDER=?");
mysqli_stmt_bind_param($stmt, 's', 'F');

Or use string manipulation to construct the query:

mysqli_stmt_prepare($stmt, "SELECT NAME FROM PERSONA WHERE $filter");
Mureinik
  • 297,002
  • 52
  • 306
  • 350
-1

The other answer is obviously wrong. As the first suggestion doesn't answer the question at all, and the second one would work only for gender. While even for a CITY would be just impossible.

So you will have to create your query dynamically.
With mysqli it's too toilsome so I'll show how to do that with PDO:

$sql = "SELECT NAME FROM PERSONA WHERE 1";
$filters = [];
$params = []
if ($gender)
{
    $filters[] = " AND GENDER=:gender";
    $params['gender'] = $gender;
}
$sql .= implode("", $filters);
$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$data = $stmt->fetchAll();
Your Common Sense
  • 156,878
  • 40
  • 214
  • 345