0

在我的 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循环内的变量一次又一次地被覆盖,直到循环终止并且我可以使用获取信息。

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

提前致谢。

4

2 回答 2

2

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

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

给予以下好处:

  • 在php中缓存rs(序列化数据)
  • 在 rs 中向后跳
于 2012-05-25T08:08:53.620 回答
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.. 
 }
于 2012-05-25T08:07:36.710 回答