Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

this foreach loop returns double the results

i am trying to run a script to get the member ids of a particular group. when i use the foreach loop it returns each result twice and sometimes will miss the last result in the database.

here is my code:

    <?php
    include_once("scripts/checkuserlog.php");
    $squadid = "";
    if (isset($_GET['pid'])){ $squadid = $_GET['pid'];};

    $sqlName = "SELECT mem_id FROM team_members WHERE team_id='$squadid' AND is_member='1'" or die ("Sorry we had a mysql error!");
    $queryName = mysqli_query($db_conx, $sqlName);
    while($array = mysqli_fetch_array($queryName)){
        foreach($array as $value){
            echo "$value<br/>";
        } 
    }
    ?>

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <title>Untitled Document</title>
    </head>
    <body>
    </body>
    </html>

the result this throws up would look something like:

3
3
2
2
1
1
4
4
5
5

obviously there should only be one of each number as each member can only join each group once.

i have never really used foreach loops before no am not 100% sure on their working, i have done a bit of research on the syntax but cant work out where i am going wrong. i can only assume i am calling something twice but not sure where.

if anyone knows of a better method to achieve what i need other than a foreach loop i am all ears

thanks

like image 520
dyer926 Avatar asked Mar 24 '26 11:03

dyer926


2 Answers

Try with mysqli_fetch_assoc instead, msqli_fetch_array returns numeric keys and strings.

<?php
include_once("scripts/checkuserlog.php");
$squadid = "";
if (isset($_GET['pid'])){ $squadid = $_GET['pid'];};

$sqlName = "SELECT mem_id FROM team_members WHERE team_id='$squadid' AND is_member='1'" or die ("Sorry we had a mysql error!");
$queryName = mysqli_query($db_conx, $sqlName);
while($array = mysqli_fetch_assoc($queryName)){
    foreach($array as $value){
        echo "$value<br/>";
    } 
}
?>
like image 91
arielcr Avatar answered Mar 27 '26 02:03

arielcr


The answer is simple. This is because two kinds of results are fetched:

  1. Associative Array, e.g. array["key"]
  2. Indexed Array, e.g. array[0]

Use mysqli_fetch_assoc if you want associative array

Use mysqli_fetch_row if you want indexed array

like image 36
Prashant Ghimire Avatar answered Mar 27 '26 02:03

Prashant Ghimire



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!