2011-06-28 38 views
0

我似乎無法得到'選擇的項目'的值傳遞給PHP函數,該函數使用該值從MySQL數據庫查詢數據 - >填充不同的下拉列表。無法獲得選擇項目的價值?

這裏是我的 'HTML' 代碼

<select name="numbers" id="numbers" onChange="populateOtherSelect()"> 
    <option value="one">one</option> 
    <option value="two">two</option> 
    <option value="three">three</option> 
    <option value="four">four</option> 
</select> 

<?php echo $option ?> 

這裏是我的 '的JavaScript' 功能代碼

function populateOtherSelect() { 
<?php 
    // code that opens db connection 

    $numbers = $_POST['numbers']; 

    $query = "select*from Database.Table where Something = 'Something' and Numbers like '%".$numbers."%'"; 

    $result = mysql_query($query); 

    $option = ""; 

    while($row = mysql_fetch_array($result)) 
    { 
     $OtherOptions = $row["OtherOptions"]; 
     $option.="<option value=\"$OtherOptions\">".$OtherOptions."</option>\r\n"; 
    } 

    // code that closes db connection 
?> 

}

任何信息都將是有益的。

非常感謝

+0

那麼,有什麼問題呢? '$ numbers'是否爲空,或者您對查詢有問題嗎? – joakimdahlstrom

+0

是的,$數字是空的。 – TheRealDK

+0

如果您想像現在這樣做,您必須發佈表單,每次更改列表時都會導致網站重新加載。否則,它是AJAX ..看看@ jeroen的答案。 – joakimdahlstrom

回答

2

看來你的javascript代碼是html/php文檔的一部分,這不會起作用; PHP只在初始頁面加載時運行,並且此時可能沒有$_POST變量。

你需要做的是在你的第一個選擇被改變的時候調用一個PHP腳本的ajax調用,並使用來自該Ajax調用的響應填充你的第二個選擇。

所以基本上你的JavaScript函數必須看起來像:

function populateOtherSelect() { 
    /* 
    * 1. get the value of the numbers select 
    * 2. make an ajax call to a php script/the server that gets some information from a database 
    * 3. use the response from the ajax call to populate your second select 
    */ 
} 
+0

+1剛剛意識到他有'onChange'調用一個PHP函數。 – joakimdahlstrom

0

我認爲你需要在你的SELECT語句中加上一個空格:

所有的
$query = "select * from Database.Table where Something = 'Something' and Numbers like '%".$Numbers."%'"; 
0

首先,$Numbers變量不存在,這是$numbers

+0

好吧,我改變了代碼,以便更容易遵循所有命名具有相同的情況。 – TheRealDK