Combine PHP prepared statments with LIKE

后端 未结 6 1763
南方客
南方客 2020-12-02 00:12

Anyone know how to combine PHP prepared statements with LIKE? i.e.

\"SELECT * FROM table WHERE name LIKE %?%\";

相关标签:
6条回答
  • 2020-12-02 00:48

    The % signs need to go in the variable that you assign to the parameter, instead of in the query.

    I don't know if you're using mysqli or PDO, but with PDO it would be something like:

    $st = $db->prepare("SELECT * FROM table WHERE name LIKE ?");
    $st->execute(array('%'.$test_string.'%'));
    

    EDIT :: For mysqli user the following.

    $test_string = '%' . $test_string . '%';
    $st->bind_param('s', $test_string);
    $st->execute();
    
    0 讨论(0)
  • 2020-12-02 00:52

    You can use the concatenation operator of your respective sql database:

    # oracle
    SELECT * FROM table WHERE name LIKE '%' || :param || '%'
    # mysql
    SELECT * from table WHERE name LIKE CONCAT('%', :param, '%')
    

    I'm not familar with other databases, but they probably have an equivalent function/operator.

    0 讨论(0)
  • 2020-12-02 00:54

    You could try something like this:

    "SELECT * FROM table WHERE name LIKE CONCAT(CONCAT('%',?),'%')"
    
    0 讨论(0)
  • 2020-12-02 00:54

    in PHP using MYSQLI you need to define a new parameter which will be declared as:

    $stmt = mysqli_prepare($con,"SELECT * FROM table WHERE name LIKE ?");
    $newParameter='%'.$query.'%';
    mysqli_stmt_bind_param($stmt, "s", $newParameter);
    mysqli_stmt_execute($stmt);
    

    this works for me..

    0 讨论(0)
  • 2020-12-02 00:58

    For me working great, I've looked for answer hours, thx.

        $dbPassword = "pass";
        $dbUserName = "dbusr";
        $dbServer = "localhost";
        $dbName = "mydb";
    
        $connection = new mysqli($dbServer, $dbUserName, $dbPassword, $dbName);
    
        if($connection->connect_errno)
        {
            exit("Database Connection Failed. Reason: ".$connection->connect_error);
        }
            $tempFirstName = "reuel";
        $sql = "SELECT first_name, last_name, pen_name FROM authors WHERE first_name LIKE CONCAT(CONCAT('%',?),'%')";
        //echo $sql;
    
        $stateObj = $connection->prepare($sql);
        $stateObj->bind_param("s",$tempFirstName);
        $stateObj->execute();
        $stateObj->bind_result($first,$last,$pen);
        $stateObj->store_result();
    
        if($stateObj->num_rows > 0) {
            while($stateObj->fetch()){
                echo "$first, $last \"$pen\"";
                echo '<br>';
            }
        }
    
        $stateObj->close();
        $connection->close();
    
    0 讨论(0)
  • 2020-12-02 00:58

    I will just adapt Chad Birch's answer for people like me who are used to utilize bindValue(...) for PDO:

    $st = $db->prepare("SELECT * FROM table WHERE name LIKE :name");
    $st->bindValue(':name','%'.$name.'%',PDO::PARAM_STR);
    $st->execute();
    
    0 讨论(0)
提交回复
热议问题