0

我有两张表,一张包含一天中所有可用的工作时间,另一张表包含有人说他们可用的时间。当我创建我的<select>表单字段时,我想自动选择该日期和时间的数据库中已经存在的tutor_id时间tutor_ availability

      hours_list                                tutor_availability
----------------------               --------------------------------------       
  24hour   |   12hour                tutor_id | day | start_time | end_time
----------------------               --------------------------------------
  1000     |   10:00am                 27     | mon |   1000     |   1100
----------------------               --------------------------------------
  1030     |   10:30am
----------------------
  1100     |   11:00am
----------------------
  1130     |   11:30am
----------------------
//the list goes on

我用Left Join's 尝试了几个查询,但收效甚微。我在想我可以做两个单独的查询,但后来我遇到了如何在迭代结果时选择正确的选项字段的问题hours_list

$hours = Select * FROM hours_list;
//next query
$available = Select day, start_time, end_time 
FROM tutor_availability WHERE tutorid = '27';

foreach ($hours as $option) { 
echo '<option value="' . $option['24hour'] . '"';
if ($available['start_time'] == $option['24hours'] && $available['day'] == 'mon') {   
echo 'selected'; }
//rest here

但是,我不知道如何同时迭代两个 sql 结果以获得正确的结果。

4

2 回答 2

0
$hours  = array();
$avail  = array();
$query  = mysql_query("Select * FROM hours_list");

while($result = mysql_fetch_assoc($query)){
   $hours[]   = $result['24hour'] 
}

$available = mysql_query("Select day, start_time, end_time 
FROM tutor_availability WHERE tutorid = '27'");

while($res  = mysql_fetch_assoc($available)){
    $avail[] = $res['start_time'];
}


foreach($hours as $hour){
echo '<option value="' . $hour . '"';
if (in_array($hour, $avail)) {   
echo 'selected >'.$hour.' </option>';
}
于 2013-01-22T05:41:49.357 回答
0

如果您仅在这么小的范围内使用数据库,我认为无需触发 JOIN 查询。但始终使用 mysqli_* 函数,因为 mysql_* 自 PHP 5.5.0 起已弃用。(参考这里)下面是所需的代码。

    //Connect to db
    $link =mysqli_connect("localhost", "root", "", "test");

    // Get all hours record as all are needed in dropdown
    $hours = mysqli_query($link, "SELECT * FROM hours_list");

    // Get desired tutor record as it is to be shown as selected
    $tut=mysqli_query($link, "SELECT * FROM tutor_availability WHERE tut_id=27");
    $tut1= mysqli_fetch_assoc($tut);

    //echo dropdown script
    echo "<select name='testSelect'>";
    while($row=mysqli_fetch_assoc($hours)){

        echo '<option value="' . $row['twentyFourHour']. '" ';
        if ($tut1['start_time'] == $row['twentyFourHour'] && $tut1['day'] == 'mon') {
            //show this option as selected.
            echo ' selected ';
        }
        echo ">".$row['twelveHour']."</option>";
    }
    echo "</select>";
于 2013-01-22T06:14:05.887 回答