Search code examples
phpprepared-statement

Using LIKE for prepared statements


I am trying to update a column in my table with a prepared statement. I have to use LIKE and wildcards but for some reason nothing it's not working. I tried a few different ways from this site and different ones. I'm trying to upgrade from a non prepared statement to a prepared one. This is how it originally worked:

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

This is how I'm trying to make it work:

$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();

I also tried the following blocks:

$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();

Solution

  • The issue is with your $likeVar variable.

    With this statement, $likeVar = '%' . $_POST['post_id'] . '%'; you set $likeVar to a String.

    Whereas in your $opened_query->bind_param("si", $userLoggedIn, $likeVar);, you pass an argument as i, to treat $likeVar as an Integer.

    Change your statement to replace the param type as String (s) and it should work:

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