mrpatg
mrpatg

Reputation: 10117

php function to return SQL results

This is what i have

function GetEventsList(){
    $result = mysql_query("SELECT * FROM `events`") or trigger_error(mysql_error()); 
    while($row = mysql_fetch_array($result)){ 
    foreach($row AS $key => $value) { $row[$key] = stripslashes($value); } 
    $id = $row['id'];
    $en = $row['name'];
    $endt = $row['date'];
    $push = "<option value=$id>$en - $endt</option>";
    return $push;
    }
    }

Its only returning 1 result, when there are 3 in the table

Upvotes: 1

Views: 381

Answers (3)

Will
Will

Reputation: 2358

Either use echo $push in your foreach loop; or put each iteration of the option element into an array, then insert the array as needed.

Upvotes: 0

Joey Adams
Joey Adams

Reputation: 43380

If I'm reading the code correctly, return $push; is exiting the while loop prematurely. You want to return only after all results are gathered and stored in something.

Upvotes: 2

cletus
cletus

Reputation: 625087

That's because you're returning from the function at the end of the first iteration. Try:

function GetEventsList() {
  $result = mysql_query("SELECT * FROM `events`") or trigger_error(mysql_error()); 
  $push = '';
  while ($row = mysql_fetch_array($result)) {
    foreach($row AS $key => $value) {
      $row[$key] = stripslashes($value); 
    }
    $id = $row['id'];
    $en = $row['name'];
    $endt = $row['date'];
    $push .= "<option value=$id>$en - $endt</option>";
  }
  return $push;
}

On a side note: if you used good formatting/indenting that would've been far easier for you to spot.

Also, are you sure you need to use stripslashes()?

Upvotes: 4

Related Questions