0

here is my problem... i am trying to return multiple rows without refreshing the page from my a PDO statement using the 'LIKE' CLAUSE, the problem is it only returns one row and not the rest...can somebody please help me? thanks in advance

Here is my html form:

<h2>Please insert the username you would like to search for</h2>

<div align="center" id="loader_div"><span id="search_result"></span></div>

<form action="send/search.php" method="post" id="search_form">
<input type="text" id="search_username" name="get_name" />
<input type="submit" name="submitsearch" />
</form>    
<div id="get_users">

</div>

My PHP is as follows:

$search = $_POST['get_name'];

$query = $db->prepare("SELECT *
                         FROM `users`
                         WHERE `users`.`username` LIKE ? LIMIT 10");

$query->bindValue(1, "%".$search."%", PDO::PARAM_STR);

try {
     $query->execute();

     $data['success'] = true;

     while($row = $query->fetch(PDO::FETCH_OBJ)) {

     $data['users'] = " ".$row->username." ";

     echo json_encode($data);   
     exit(); 
     }

} catch (PDOException $e) {
  die($e->getMessage());     
  exit();
}

And here is my jQuery to return the PHP results:

$.ajax ({
type: "POST",
url: "send/search.php",
data: $('#search_form').serialize(),
dataType: "json",
success: function(data){
        if(data.success === true)
        {
          $("#display_users").html(data.users);
        },
error: function(xhr, status, et) {

    }
});
1
  • 1
    Note, you can't just concatenate JSON together and have it be valid. {"a":"b"}{"a":"c"}, for example, is invalid. Gather the results in an array and encode that, and it should work better. As for why there's only one row either way...you do know what exit() does, right? Commented Sep 13, 2012 at 19:30

1 Answer 1

2

The json_encode and exit should be outside the while loop:

while($row = $query->fetch(PDO::FETCH_OBJ)) {

     $data['users'] .= " ".$row->username." ";    
}

echo json_encode($data);   
exit(); 

Denpending on what format you need on the client side you decide on what to do with the $data['users'], this is also a option:

$data['users'][] = " ".$row->username." ";
Sign up to request clarification or add additional context in comments.

1 Comment

First of all i just wanna say thank you guys for your speedy and rapid response @JvdBerg i just changed the line: $data['users'] = " ".$row->username." "; To: $data['users'][] = " ".$row->username." "; and it finally worked!!!! once again thank you for your help and time

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.