问题
How to bind unknown number of parameters with Mysqli? For example, following my code:
<?php
include 'config.php';
$query = "SELECT * FROM table WHERE";
if(isset($_POST['r1']))
$query = $query." id = '$_POST['r1']'";
if(isset($_POST['r2']))
$query = $query." AND par2 = '$_POST['r2']'";
$e = mysqli_prepare($conf, $query);
?>
How to do bind of parameters?
回答1:
Prepared statements probably aren't the best way to do this. You can assemble a query just as you are doing, as long as you make sure that you escape any user input. For example:
<?php
// assuming $db is a mysqli object
$query = "SELECT * FROM table WHERE";
if(isset($_POST['r1']))
$query = $query."id = '".$db->real_escape_string($_POST['r1'])."'";
if(isset($_POST['r2']))
$query = $query." AND par2 = '".$db->real_escape_string($_POST['r2'])."'";
$result = $db->query($query);
?>
Don't forget to add any required error checking.
来源:https://stackoverflow.com/questions/20180214/mysqli-bind-unknown-number-of-parameters