在MySQL预处理语句中的WHERE子句中使用通配符

时间:2014-12-15 14:41:19

标签: php mysql sql mysqli

我有以下MySQL声明:

$sql = "SELECT * FROM `table` WHERE `field`=?;";
$prepare = $connect -> prepare( $sql );
$prepare -> bind_param( "i" , $value );
$value = $_GET["value"];
//etc.

但是,“未过滤”是一种选择。有没有办法将通配符传递给语句,如:

if ( ! isset ( $_GET["value"] ) ) $value = SOME_WILDCARD_INDICATOR;

...或者我是否必须为未经过滤的查询设置一个完整的代码块?

3 个答案:

答案 0 :(得分:1)

正如其他人所说,如果值存在,您只想添加where条件。

<?php

$sql = "SELECT * FROM `table`";
$value = $_GET['value'];

if ($value)
{
  $sql .= " WHERE `field` = ?"
}

$query = $db->prepare ($sql);

if ($value)
{
  $query->bind_param ('i', $value);
}

答案 1 :(得分:1)

只需使用一点逻辑 -

$value = $_GET["value"];
$sql = "SELECT * FROM `table`";
if (isset($value)) {
    $sql .= "WHERE `field`=?";
    $prepare -> bind_param( "i" , $value );
}
$sql .= ";";

答案 2 :(得分:1)

当你说“添加一些逻辑”时,@ Jay-Blanchard,我认为你的意思是这样,而且它完美无缺:

$filter = " WHERE 0=?";
$value = 0;

if ( isset ( $_GET["value"] ) )
{   
    $filter = " WHERE `field`=?";
    $value = $_GET["value"];
}

$sql = "SELECT * FROM `table`" . $filter . ";";
$prepare = $connect -> prepare( $sql );
$prepare -> bind_param( "i" , $value );

//etc.

好灵感!