对准备好的语句使用 LIKE

Using LIKE for prepared statements

我正在尝试使用准备好的语句更新 table 中的列。我必须使用 LIKE 和通配符,但由于某种原因它不起作用。我从这个站点尝试了几种不同的方法和不同的方法。我正在尝试从非准备好的语句升级到准备好的语句。这是它最初的工作方式:

$opened_query = mysqli_query($this->con, "UPDATE notifications SET opened='yes' WHERE 
user_to='$userLoggedIn' AND link LIKE '%=$post_id'");

这就是我努力让它发挥作用的方式:

$post_id = '%' . $post_id . '%';
    $opened_query = $this->con->prepare('UPDATE notifications SET opened="yes" WHERE 
        user_to = ? AND link LIKE ?');
    $opened_query->bind_param("si", $userLoggedIn, $post_id);
    $opened_query->execute();
    $opened_query_result = $opened_query->get_result();

我还尝试了以下块:

$post_id = '%' . $post_id . '%';
    $opened_query = $this->con->prepare('UPDATE notifications SET opened="yes" WHERE 
        user_to = ? AND link LIKE ?');
    $opened_query->bind_param("si", $userLoggedIn, $post_id);
    $opened_query->execute();

$post_id = '%' . $_POST['link'] . '%';
    $opened_query = $this->con->prepare('UPDATE notifications SET opened="yes" WHERE 
        user_to = ? AND link LIKE ?');
    $opened_query->bind_param("si", $userLoggedIn, $post_id);
    $opened_query->execute();
    $opened_query_result = $opened_query->get_result();

$likeVar = '%' . $_POST['post_id'] . '%';
    $opened_query = $this->con->prepare('UPDATE notifications SET opened="yes" WHERE 
        user_to = ? AND link LIKE ?');
    $opened_query->bind_param("si", $userLoggedIn, $likeVar);
    $opened_query->execute();
    $opened_query_result = $opened_query->get_result();

问题出在您的 $likeVar 变量上。

使用此语句,$likeVar = '%' . $_POST['post_id'] . '%'; 您将 $likeVar 设置为 String

而在您的 $opened_query->bind_param("si", $userLoggedIn, $likeVar); 中,您将参数作为 i 传递,以将 $likeVar 视为 Integer

更改您的语句以将参数类型替换为 String (s),它应该可以工作:

$opened_query->bind_param("ss", $userLoggedIn, $likeVar);