我有一個PHP代碼,我有一個SQL數據庫中的國家列表的下拉列表。該值進行排序:
Continent (Row 1) - > Country (Row 2) -> City (Row 3)
EG。
Europe -> England -> London
Europe -> England -> London
Europe -> Gemany -> Munich
North America -> New York -> Manhattan
North America -> California -> Los Angeles
這是我當我選擇大陸第一
$dbh->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
$tableName = 'categories';
ob_start();
session_start();
//Get values from table
$sqlPrimaryCategory = $dbh->prepare("SELECT * FROM $tableName GROUP BY primary_category");
$sqlPrimaryCategory->execute();
echo '<form id="primary_category" name="primary_category" action="" method="post">';
echo '<select name="primary_category" onChange="this.form.submit()" size = "4"> ';
while ($result = $sqlPrimaryCategory->fetch()) {
echo '<option value="';
echo $result['primary_category'];
echo '">';
echo $result['primary_category'];
echo '</option>';
}
echo '</select>';
echo '</form>';
echo '<p><strong>You have selected</strong> <em>'.$_POST['primary_category'].'</em></p>';
$_SESSION['primary_category'] = $_POST['primary_category'];
echo 'Your selection is ' . $_SESSION['primary_category'];
$primaryCategory = $_SESSION['primary_category'];
然後根據第一個值我去例如選擇第二個值碼如果我選擇歐洲 - 我會選擇英國或德國之間的選擇。
這是用我的第二個代碼,以獲得第二值
//Get values from table
$sqlSecondaryCategory = $dbh->prepare("SELECT * FROM $tableName WHERE primary_category = :primary_category GROUP BY secondary_category");
$sqlSecondaryCategory->execute(array(':primary_category'=>$primaryCategory));
echo '<form action="" method="post">';
echo '<select name="secondary_category" onChange="this.form.submit()" size = "4"> ';
while ($result = $sqlSecondaryCategory->fetch()) {
echo '<option value="';
echo $result['secondary_category'];
echo '">';
echo $result['secondary_category'];
echo '</option>';
}
echo '</select>';
echo '</form>';
echo '<p><strong>You have selected</strong> <em>'.$_POST['secondary_category'].'</em></p>';
$_SESSION['secondary_category'] = $_POST['secondary_category'];
echo 'Your selection is ' . $_SESSION['secondary_category'];
$secondaryCategory = $_SESSION['secondary_category'];
不幸的是,當我在第二類,即該國從$_SESSION['primary_category']
選擇的價值,只有在顯示$_SESSION['secondary_country']
完成。
我想,當我選擇說歐洲,$_SESSION['primary_category']
保留。
我的懷疑是因爲他們兩個HTML表單都包含onChange="this.form.submit()"
每個,一個是刪除另一個。
我想如果我改變onChange="this.form.submit()"
並且是基於表單名稱或id提交的,我不會有這個問題。不幸的是,我不熟悉JavaScript
開始使用error_reporting(E_ALL)爲您的開發!也許你應該修復「FROM $ tableName」,至少它會搞砸了,或者如果(空的($ _ POST ['primary_category'])){$ _ SESSION ['primary_category'] = $ _POST ['primary_category'];} 性能/緩存.. – hanshenrik