fedesc
fedesc

Reputation: 2610

PHP Getting a variable outside from a while loop

in my PHP script i make a mysql_query :

  $full_alarm_sql = "
          SELECT alarms.id, alarms.date, clients.name, clients.number, alarms.controller, alarmstype.type, 
          alarms.alarmstatus, alarms.starttime, alarms.endtime, DATEDIFF(CURDATE(), alarms.date) AS difference
          FROM alarms
          LEFT JOIN clients ON alarms.clientid = clients.id
          LEFT JOIN alarmstype ON alarms.typeid = alarmstype.id
          WHERE DATEDIFF(CURDATE(), alarms.date) <=" . $type . " AND clients.number = " . $market;
  $full_alarm_query = mysql_query($full_alarm_sql);

and then i make a while loop inside a table with the fetching of the query :

while ($full_alarm_fetch = mysql_fetch_array($full_alarm_query)) {
  $content .=
    "
           <tr>
          <td>" . $full_alarm_fetch['date'] . "</td>
          <td>" . $full_alarm_fetch['number'] . " | " . $full_alarm_fetch['name'] . "</td>
          <td>" . $full_alarm_fetch['controller'] . "</td>
          <td>" . $full_alarm_fetch['type'] . "</td>
          <td>" . $full_alarm_fetch['alarmstatus'] . "</td>
          <td>" . $full_alarm_fetch['starttime'] . "</td>
          <td>" . $full_alarm_fetch['endtime'] . "</td>
        </tr>";
   $client_name = $full_alarm_fetch['name'] . ' | ' . $full_alarm_fetch['number'];
}

and then i need to use

$full_alarm_fetch['name'] . ' | ' . $full_alarm_fetch['number'];

so the way i'm doing it now just doesn't seem the best way, meaning the variable inside the while loop is overwritten time and time again until the loop dies and than i can user the fetch information.

i was wondering if there is a better/efficient way of doing what i'm trying to do.

thanks in advance.

Upvotes: 0

Views: 1725

Answers (2)

Teson
Teson

Reputation: 6736

Your code is fine. You could grab the whole rs at once, and then loop it,

while ($rs[] = mysql_fetch..);
//done..
for($i=0;$i<sizeof($rs);$i++) or
foreach($rs as $rec)

giving the benefits of:

  • cache the rs at php (serialized data)
  • jump backwards in rs

Upvotes: 2

Sevag Akelian
Sevag Akelian

Reputation: 231

Yes there is a better way. You can first declare an array and save the fetched content there and then loop through the array. like this.

 $fetched_arr = array();
while ($full_alarm_fetch = mysql_fetch_array($full_alarm_query)) {
  $fetched_arr[] = $full_alarm_fetch;
}

then you loop the array

foreach($fetched_array as $something)
 {
    //here you can save the values in the $content
    // you can use $somethin['date'] and etc.. 
 }

Upvotes: 1

Related Questions