在PHP創建函數生成選項(發送HTML是不好的做法,但我適應這個例子)。在這個特殊的例子,我建議創建的functions.php文件,並有增加printSelectOptions函數聲明:
function printSelectOptions(){
$result = mysql_query("select * from rtable r
inner join table_status as ts
on ts.status_id=r.status_id
where ts.status!='Booked'
order by r.table_id desc")or die(mysql_error());
echo "<option disabled='disabled'>Select Table</option>";
while ($row=mysql_fetch_array($result)){
echo "<option value=".$row['table_id'].">".$row['table_name']."</option>";
}
}
以上功能的打印所有HTML選項選擇。
使用它的功能生成選擇(記住functions.php中應包含與printSelectOptions的使用的任何文件):
<?php
//db connection code
require_once("functions.php");//here we add our function to be available in this file
?>
<select name="table_id" class="form-control tablename">
<?php printSelectOptions() ?>
</select>
在前端綁定你的選擇(javascript代碼):
document.addEventListener("DOMContentLoaded", function(event) {
var select=document.querySelector("select"); //this is pure selector gets first select on page
//function sends ajax and refresh options of select
function refreshOptions(){
//send ajax request
select.innerHTML="<option>Loading..</option>"; //loading info
var xmlhttp=new XMLHttpRequest();
xmlhttp.open("GET", 'yourSecondPHPScript.php');//here example url where we get updated options
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == XMLHttpRequest.DONE) {
if(xmlhttp.status == 200){
select.innerHTML = xmlhttp.responseText;//set new options
}else{
console.log('Error: ' + xmlhttp.statusText)
select.innerHTML="<option>Connection problem</option>";
}
}
}
xmlhttp.send();
};
//bind our select
select.addEventListener("focus",function(){
refreshOptions();
});
});
末創建例如yourSecondPHPScript.php,並在其中使用功能:
<?php
//db connection code
require_once("functions.php");//here we add our function to be available in this file
printSelectOptions();//outputs options
要確保用戶不會採取相同的表,除了在重點檢查一些提交訂單的檢查一遍。所以如果表被刷新選擇(通過ajax使用refreshOptions())並顯示該表是否已被採用。
最後一件事是確保它在服務器端,在PHP創建一些檢查功能(PHP代碼):
function tableCanBeTaken($optionId){
//this code adds **and** to query with id to check but optionId should be validate before using in query
$result = mysql_query("select * from rtable r
inner join table_status as ts
on ts.status_id=r.status_id
where ts.status!='Booked'
and ts.table_id=$optionId ")or die(mysql_error());
return mysql_fetch_array($result); //if row exists - will be false if not exists row with table_id==$optionId and not booked
}
}
然後使用它(PHP代碼):
if (tableCanBeTaken($youOptionId)){
//here code for taking option
}else{
//here option is taken
}
所以你嘗試過什麼相同的代碼? – coder
那麼你可以使用Ajax,SQL和PHP?..解釋你所嘗試的將是一個好開始 – Satty
想要開始與AJAX。 –