简体   繁体   中英

How should I write SQL query that contains LIKE in PHP?

I want to make a query that ends in LIKE value% , but for some reason, there is an error with it.

$_GET['letter'] contains the starting letter that I want to use in my query.

For example if its 'a' , my query will be ...WHERE name LIKE 'a%' .

My code:

$sql = sprintf("SELECT id, name, username, email FROM users WHERE name LIKE '" . ($_GET['letter']) . "%'");

The error I get is: PHP Warning: sprintf(): Too few arguments

And then of course: PHP Warning: mysqli::query(): Empty query

Thanks in advance.

Don't even consider taking this route. Use prepared statements with PDO or mysqli instead.

if(isset($_GET['letter']) && strlen($_GET['letter']) > 0) {
    $letter = $_GET['letter'] . '%';
    $sql = "SELECT id, name, username, email FROM users WHERE name LIKE ?";
    $query = $con->prepare($sql);
    $query->bind_param('s', $letter);
    $query->execute();

    $query->bind_result($id, $name, $username, $email);
    while($query->fetch()) {
        echo $id . '<br/>';
        // and others
    }

    // alternate version with mysqlnd installed
    // $results = $query->get_result();
    // while($row = $results->fetch_assoc()) {
    //  echo $row['id'];
    // }
} else {
    echo 'please provide for search value';
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM