php mysqli prepared statement LIKE

前端 未结 2 698
时光说笑
时光说笑 2020-11-22 06:53

How can I with mysqli make a query with LIKE and get all results?

This is my code but it dosn\'t work:

$param = \"%{$_POST[\'user\']}%\";
$stmt = $db         


        
2条回答
  •  盖世英雄少女心
    2020-11-22 07:31

    Here's how you properly fetch the result

    $param = "%{$_POST['user']}%";
    $stmt = $db->prepare("SELECT id,username FROM users WHERE username LIKE ?");
    $stmt->bind_param("s", $param);
    $stmt->execute();
    $stmt->bind_result($id,$username);
    
    while ($stmt->fetch()) {
      echo "Id: {$id}, Username: {$username}";
    }
    

    or you can also do:

    $param = "%{$_POST['user']}%";
    $stmt = $db->prepare("SELECT id, username FROM users WHERE username LIKE ?");
    $stmt->bind_param("s", $param);
    $stmt->execute();
    
    $result = $stmt->get_result();
    while ($row = $result->fetch_assoc()) {
        echo "Id: {$row['id']}, Username: {$row['username']}";
    }
    

    I hope you realise I got the answer directly from the manual here and here, which is where you should've gone first.

提交回复
热议问题