0v3k Shi3ld3r 0v3k Shi3ld3r - 4 months ago 15
SQL Question

Repeating Results PHP Query While Loop

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>
</html>



Answer

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;
Comments