从MSSQL中引用PHP数组


Referencing PHP array from MSSQL

使用MSSQL和PHP,我正在编写一个日历表单,该表单列出了用户时间表中的时间,并允许他输入他是否忙,是否有空等。

一旦用户提交信息,它将被保存到数据库。

如果用户返回到表单,他应该看到表单字段默认为他已经输入的值。

好的,所以我可以查询数据库的每一天和时间段,并使用结果来确定表单上显示的内容…但这是145次对数据库的调用,因为这是用户在一周内可以使用的时间段数。

似乎应该有一种方法可以查询数据库一次,将145个结果存储在一个数组中,然后按日期和时间查询每个字段的数组。

我得到:

$sql="SELECT * FROM committee_employee_schedules WHERE fac_id = $user_id";
$result= mssql_query($sql,$conn);

但是从那里我不想进入一个while循环与mssql_fetch_array()…我该如何查询结果集呢?谢谢。

这里有一些更多的示例代码,因为我似乎无法沟通:

<form>
<label for="7:30AM">7:30AM</label>
<select name="7:30AM">
<option>Available</option>
<option>Class</option>
<option>Office Hours</option>
</select>
<label for="8:00AM">8:00AM</label>
<select name="8:00AM">
<option>Available</option>
<option>Class</option>
<option>Office Hours</option>
</select>
<label for="8:30AM">8:30AM</label>
<select name="8:30AM">
<option>Available</option>
<option>Class</option>
<option>Office Hours</option>
</select>
</form>

…这一直持续到周一至周五晚上9:30,总共有145个下拉字段。

每个字段都需要知道表中是否存在该时间段的行,如果存在,则选择适当的活动。

我可以使用上面的代码抓取用户的所有记录,但是我是否必须为表单上的每个字段循环这145行?有没有一种方法可以将记录粘贴到数组中并引用结果['Monday']['7:30'][Activity]或其他东西?

那么,您将从数据库返回145条记录。SELECT查询的结果将存储在一个数组中,您必须使用循环遍历它们。这个循环可以从记录中读取日期和时间段,并将其存储到一个适当的数组中。稍后,您可以以您想要的方式引用该新数组。我将试着在下面列出一个近似的例子。

<?php
    slotData = array();//Store your results here the way you want to, see down below
    $sql="SELECT * FROM committee_employee_schedules WHERE fac_id = $user_id";
    $result= mssql_query($sql,$conn);
    while($row = mssql_fetch_row($result)) {
        $day = $row['day'];//Guessing your column name here
        $time = $row['time_of_day'];//again, guessing your time here
        $slotData[$day][$time] = $row;
        //this all assumes "$day" looks like "monday", "tuesday", etc.
        //also assumes "$time" looks like "8:00AM", "9:30PM", etc.
    }
    //now that data is in array the way you want, reference it later
    //Assume you are currently trying to populate Monday at 8am position in calendar...
    $curDay = 'monday';
    $curTime = '8:00AM';
    $data = $slotData[$curDay][$curTime];
    //Yeay! "$data" now has all of the information for Monday at 8am.
?>

底线是,遍历数据库结果集并将数据移动到不同数组的适当槽中,这取决于它应该放在哪里。然后,引用不同的数组,但你喜欢不用担心每次迭代所有的原始记录。解决。