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

Web Development

This is my code but it dosn't work:

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

This code it doesn't seem to work. I have searched it a lot. Also it may return more than 1 row. So how can I get all the results even if it returns more than 1 row?
 


If you want to unleash your potential in this competitive field, please visit the Web Development course page for more information, where you can find the Web Development tutorials and Web Development frequently asked interview questions and answers as well.

1
Answers

Replies

Ans: You can obtain the results in two different ways


Way -1:


$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}";

}

Way -2:


$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']}";


}

 
 

This topic has been locked/unapproved. No replies allowed

Login to participate in this discussion.

Leave a reply

Before proceeding, please check your email for a verification link. If you did not receive the email, click here to request another.
To Top