使用%通配符的Mysqli准备语句

时间:2017-06-15 15:28:20

标签: php mysql mysqli wildcard sql-like

我正在尝试构建一个动态预准备语句,以便我可以重用代码。我在准备状态下使用%?%时遇到问题,因为它使用了LIKE。我的代码如下:

$where = " First_Name LIKE '%?%' ";
$vals = array('Mike');
$type = 's';

$dbd = mysqli_stmt_init($dbconnection);
if (mysqli_stmt_prepare($dbd, "SELECT * FROM Contacts WHERE $where" )) {
mysqli_stmt_bind_param($dbd, $type, ...$vals);
if (!mysqli_stmt_execute($dbd)) {
echo "Execute Error: " . mysqli_error($dbconnection);
        } else {
            //do nothing
        }
    } else {
        echo "Prep Error: " . mysqli_error($dbconnection);
    }
mysqli_stmt_get_result($dbd);

所以当我使用" First_Name =?"它工作正常所以我认为我的问题是'%?%'。我已经搜索过决议但却无法找到与我的动态准备陈述相关的任何内容。谢谢你的帮助。

1 个答案:

答案 0 :(得分:1)

您需要绑定完整的值,而不仅仅是它的一部分。这意味着:

$where = "First_Name LIKE ?"

然后绑定:

$vals = array('%Mike%');