mysql php做循环方法

时间:2013-12-15 00:03:36

标签: php mysql

嗨,我是php代码的新手,这是我想解决的问题

  1. 假设我们有事件[eid,pid,start_time,end_time,date] = [kim,34:00:00:00,4:00:00,2013-12-25]
  2. 如果我想打印某个日期的'范围'。 例如,我输入日期,如

    开始= 2012-12-23 结束= 2012-12-25

    我希望打印这些日期之间的所有事件。 我应该把一些for循环功能放到查询中吗?或

    $result2 =mysql_query("
    select eid,description
    from event natural join eventdate
    where pid = '$pid'
    and edate = '$edate'
    }
    

    或在这里

    if($myrow = mysql_fetch_array($result))
    {
      echo"<table border=1>\n";
      echo"<tr><th>pid<th>edate<th>description<th> schedule I invited and accept</tr>\n";
      do{
        printf("<tr><td>%s<td>%s<td>%s<td></tr>\n",$myrow["pid"],$myrow["edate"],$myrow["description"]);
      }while($myrow = mysql_fetch_array($result));
    

1 个答案:

答案 0 :(得分:2)

如果您要选择edate属于特定日期范围的所有行,并假设edate属于date类型,则可以执行

SELECT e.eid, e.description
  FROM event e JOIN eventdate d
    ON e.eid = d.eid
 WHERE pid = '$pid'
   AND edate BETWEEN '$range_start_date' AND '$range_end_date'

旁注:请考虑使用mysqli_*PDO来学习和使用预准备语句,而不是插入查询字符串。

这是 SQLFiddle 演示


您的PHP代码可能类似于

$pid = 34;
$edate = '"2013-12-23"-"2013-12-25"';
list($range_start_date, $range_end_date) = explode('"-"', trim($edate, '"'));

$db = new mysqli('localhost', 'user', 'userpwd', 'test');
if (!$db) {
    die('Could not connect: ' . $db->connect_error); //TODO: better error handling
}

$sql = "SELECT e.eid, e.description
  FROM event e JOIN eventdate d
    ON e.eid = d.eid
 WHERE pid = ?
   AND edate BETWEEN ? AND ?";

if ($stmt = $db->prepare($sql)) {
    $stmt->bind_param('iss', $pid, $range_start_date, $range_end_date);
    $stmt->execute();
    $stmt->bind_result($eid, $description);

    while ($stmt->fetch()) {
        // Output a row
        echo "<tr><td>$pid</td><td>$eid</td><td>$description</td></tr>";
    }
    $stmt->close();
} else {
    die('Prepare failed: ' . $db->error); //TODO: better error handling
}
$db->close();