我有两个表,一个包含一天中所有可用的工作时间,另一个表包含某人表示他们可用的工作时间。当我创建<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
的几个查询但收效甚微。我想我可以做两个单独的查询,但后来我遇到了如何在迭代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结果来获得正确的结果。
答案 0 :(得分: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>';
}
答案 1 :(得分:0)
我认为如果你只使用这个小范围的数据库,就不需要激活JOIN查询。 但是从PHP 5.5.0开始,不推荐使用mysqli_ *函数作为mysql_ *。(参考here) 以下是所需的代码。
//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>";