Awesometown
Awesometown

Reputation: 19

MySQL Query only returning 1 row

So, I'm having a problem with my MySQL query. It has only been displaying the first result from a list of data from a variable. Here is what I've got

$Data='1,2,3'

$fetch = mysql_query("SELECT email FROM data WHERE uid IN ($Data) ");

if (mysql_num_rows($fetch)) {
    $emaildata = mysql_fetch_assoc($fetch);
    foreach($emaildata as $fetch2){
        echo $fetch2;
    }
} else {
    echo Failed;
}

Now, it only pulls the first result of the 3 instead of each of the 3's separate emails. Any help is appreciated, kinda new to this whole thing.

Upvotes: 0

Views: 1304

Answers (3)

doniyor
doniyor

Reputation: 37846

you should use while loop, which enables you to iterate so long as there is a next row with this:

while($row = mysqli_fetch_row($fetch)){
      echo  $row['email']
 }

CAUTION!!!: use mysqli_fetch_row as mysql_fetch_row is deprecated

Upvotes: 1

Mr. Alien
Mr. Alien

Reputation: 157284

Fetch array instead of fetching associative, and use mysqli_() instead of mysql_() which is no longer maintained by the community, also use while loop instead of foreach and use index name if any

while($emaildata = mysql_fetch_array($fetch)) {
     echo $emaildata; //Use index name if any
   }
}

Upvotes: 3

GBD
GBD

Reputation: 15981

Use as below because you have iterate $fetch through while loop which is easier

while($emaildata = mysql_fetch_assoc($fetch)){
   echo  $emaildata['email']
}

Recommendations:

1.Learn to prevent from MySQL Injections: Good Link

2.Mysql extension is not recommended for writing new code. Instead, either the mysqli or PDO_MySQL extension should be used. More reading: PHP Manual

Upvotes: 3

Related Questions