Vivek
Vivek

Reputation: 1493

Database values are repeating in for loop

I am selecting authorname from database depending on array condition. But when i return the code i saw my condition is repeating twice.

my code is here

$alpha=array('A','B','C','D','E','F');
    $countarray=sizeof($alpha);
    $alert.=$countarray;
    for ($a=0;$a<=$countarray;$a++)
    {
        $selectlist="select * from quotationauthor where Author_name Like'$alpha[$a]%'";
        $result=mysqli_query($con,$selectlist)
                or die(mysqli_error($con));
        $countauthor=countlist($result);
        if($countauthor < 1)
        {

        }
        else
        {
            $alert.="<h1>$alpha[$a]$countauthor</h1><br/>";
            while($row=mysqli_fetch_array($result))
            {
                $alert.=$row[Author_name]."<br/>";
            }
        }
    }
    return $alert;

Suppose i got A at first condition than it will search for the authorname in my database which is starting from A. I am getting the right output but my problem is database values are written twice

6
A


Albert Einstein
Abraham Lincoln
Abdul Kalam
Adolf Hitler

Albert Einstein
Abraham Lincoln
Abdul Kalam
Adolf Hitler

As you can see database values are written twice. I have checked my database and found that there is only 4 rows.

Upvotes: 1

Views: 389

Answers (1)

Ja͢ck
Ja͢ck

Reputation: 173602

The issue is here, in your for loop:

for ($a = 0; $a <= $countarray; $a++)

The loop condition should be:

$a < $countarray

What happens is that at the last iteration, the value of $alpha[$a] is null (well, implicitly); when cast to a string, the query becomes name LIKE '%' which is always true.

It would be more obvious if you had rows in your database starting with other letters, or even those that are not in the set of A - F

Upvotes: 3

Related Questions