1

I'm retrieving Data from MySQL with Ajax and PHP without refreshing , The issue is my results that are displayed duplicate . I only want one instance of a username to display back .

The table that contains username has a UNIQUE INDEX set not to allow the duplicate names however its my (I think) my while statement as I believe this is causing the results to duplicate

How can I Please ? Correct this to only display once instance of each username . Sorry in advance that I don't already Know but hopeful someone can help .

  <?php
  include('..\db.php');
  $con = mysqli_connect($dbsrvname, $dbusername, $dbpassword, $dbname);
  $q1 = mysqli_query($con,"SELECT * FROM tbl1 username");

  $data="";

  // if the search is true 
  if(isset($_POST['search']))
  {
// 
  $var = $_POST['search'];

  if($query = mysqli_query($con,"SELECT username FROMtbl1 WHERE username LIKE '%$var%'"))

  {
    // possible creating duplicate results 
    while($row = mysqli_fetch_array($query))
    {
        $data .= $data . '<div>' . $row['username'] . '</div>'; 

    }
    echo $data;
  }
  }else{
 }
?>


<html>

<head>

        <script
          src="https://code.jquery.com/jquery-3.0.0.js"
          integrity="sha256-jrPLZ+8vDxt2FnE1zvZXCkCcebI/C8Dt5xyaQBjxQIo="
          crossorigin="anonymous"></script>



        <script>

            $(function(){
                $('.input').keyup(function(){
                    var a = $('.input').val();
                    $.post('livesusers.php',{"search":a},function(data){
                        $('#display').html(data);
                    });
                });
            });

        </script>


</head>
<body>

 // form to input text  and search
  <form action= "livesusers.php" method='POST'>
    <input type="text" name="search" class='input'>
  </form>
  <div id='display' style='margin-top:100px'></div>
</body>

2
  • Do you get proper data in echo $data ? Commented Jul 4, 2016 at 13:26
  • I have tried using DISTINCT in my Query but still it duplicates + The results from $data DO show proper data Only its duplicates the names so if I have two names that start with K it will show each name twice Commented Jul 4, 2016 at 13:35

1 Answer 1

1

The error is in your while loop as you said. you are concatenating twice on each cicle.

Try to replace this:

// possible creating duplicate results 
    while($row = mysqli_fetch_array($query))
    {
        $data .= $data . '<div>' . $row['username'] . '</div>'; 

    }
    echo $data;

to this:

while($row = mysqli_fetch_array($query))
{
    $data .= '<div>' . $row['username'] . '</div>'; 

}
echo $data;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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