Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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) {

    }
});
share|improve this question
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? –  cHao Sep 13 '12 at 19:30

1 Answer 1

up vote 2 down vote accepted

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." ";
share|improve this answer
    
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 –  masonprice Sep 14 '12 at 1:37

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.