Mysqli绑定 - 参数数量未知

时间:2013-11-24 19:57:49

标签: php mysql mysqli

如何使用Mysqli绑定未知数量的参数?例如,遵循我的代码:

<?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);
?>

如何绑定参数?

1 个答案:

答案 0 :(得分:1)

准备好的陈述可能不是最好的方法。只要您确保转义任何用户输入,就可以像处理一样组合查询。例如:

<?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);
?>

不要忘记添加任何必需的错误检查。