MySqli prepare statement error when used for LIKE

前端 未结 2 1960
夕颜
夕颜 2021-01-29 10:34

I\'m trying to make a prepared statement for a LIKE query using php\'s mysqli extension. But no matter what I try, I always get this error:

Fatal error: Problem          


        
相关标签:
2条回答
  • 2021-01-29 10:52

    I would move expression after LIKE to variable:

    $param = '%somestring%';
    
    $sql = "SELECT f.*,r.slug FROM `foods` AS f
    INNER JOIN `resturants` AS r
    ON f.`rest_id` = r.`rest_id`
    WHERE f.`name` LIKE ?"
    

    UPDATE:

    Maybe this will help

    -- test.sql
    CREATE TABLE supportContacts (
         id int auto_increment primary key, 
         type varchar(20), 
         details varchar(30)
    );
    
    INSERT INTO supportContacts
    (type, details)
    VALUES
    ('Email', 'admin@sqlfiddle.com'),
    ('Twitter', '@sqlfiddle');
    
    <?php
    // test.php
    $mysqli = new mysqli("localhost", "root", "root", "test");
    $sql = 'SELECT type FROM supportContacts WHERE type LIKE ?'; // here is only ?, no %
    
    $stmt = $mysqli->prepare($sql);
    $type = 'E%'; // and here you can put % sign
    $stmt->bind_param('s', $type);
    $stmt->execute();
    $stmt->bind_result($result);
    $stmt->fetch();
    var_dump($result);
    
    0 讨论(0)
  • 2021-01-29 10:55

    Your %'s need to be encapsulated in quotes too.

    0 讨论(0)
提交回复
热议问题