PHP从while循环中获取变量

时间:2012-05-25 07:57:48

标签: php mysql

在我的PHP脚本中我创建了一个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);

然后我在一个表中创建一个while循环,并获取查询:

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'];
}

然后我需要使用

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

所以我现在这样做的方式似乎并不是最好的方式,这意味着while循环中的变量会一次又一次地被覆盖,直到循环消失并且我可以使用获取信息。

我想知道是否有更好/更有效的方法来做我想做的事。

提前谢谢。

2 个答案:

答案 0 :(得分:2)

你的代码很好。你可以一次抓住整个rs,然后循环它,

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

给予以下好处:

  • 将rs缓存在php(序列化数据)
  • 在rs
  • 中向后跳

答案 1 :(得分:1)

是的,有更好的方法。您可以先声明一个数组并将获取的内容保存在那里,然后遍历该数组。像这样。

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

然后循环数组

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