我目前正在使用php和mysql進行學校項目。我創建了一個包含三個下拉框的表單,供用戶選擇要查找的數據類型。但是,在提交表單後,我顯示結果很麻煩。這是我目前的代碼:提交PHP表單後顯示查詢結果
<?php
require_once 'connection.php';
?>
<form action="stats.php" method ="post">
<input type="hidden" name="submitted" value="true" />
<fieldset>
<legend>
Specify Date, Month, and County
</legend>
<p>
<label for="year">
Please select a year
</label>
<select name= 'year'>
<?php
$query = "select distinct year from unemployed";
$result = $conn->query($query);
while($row = $result->fetch_object()) {
echo "<option value='".$row->year."'>".$row->year."</option>";
}
?>
</select>
</p>
<p>
<label for="month">
Please select a month
<label>
<select name= 'month'>
<?php
$query = "select distinct month from unemployed";
$result = $conn->query($query);
while($row = $result->fetch_object()) {
echo "<option value='".$row->month."'>".$row->month."</option>";
}
?>
</select>
</p>
<p>
<label for="location">
Please specify a location
</label>
<select name='select'>
<?php
$query = "select * from unemployed";
$result = $conn->query($query);
while ($finfo = $result->fetch_field()) {
echo "<option value='".$finfo->name."'>".$finfo->name."</option>";
}
?>
</select>
</p>
<input type ="submit" />
</fieldset>
</form>
<?php
if (isset($_POST['submitted'])) {
include('connection.php');
$gYear = $_POST["year"];
$gMonth = $_POST["month"];
$gSelect = $_POST["select"];
$query = "select $gSelect from unemployed where year='$gYear' and month='$gMonth'";
$result = $conn->query($query) or die('error getting data');
echo"<table>";
echo "<tr><th>Year</th><th>Time</th><th>$gSelect</th></tr>";
while ($row = $result->fetch_object()){
echo "<tr><td>";
echo $row['Year'];
echo "</td><td>";
echo $row['Month'];
echo "</td><td>";
echo $row['$gSelect'];
echo "</td></tr>";
}
echo "</table";
} // end of main if statement
?>
我幾乎可以肯定我的問題在於我的while語句。我得到了表格列的標題(Year,Month,$ gSelect),但我沒有看到我的查詢結果顯示。
我曾嘗試:
while ($row = $result->fetch_object())
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC))
這些都不是爲我工作。我已經看過php.net的指導。我仍然對做什麼感到困惑。如果有人能幫助我,我會非常感激。
你確定你的查詢返回行? – crush
嘗試'var_dump($ result)'來查看你從查詢中得到的結果。您也應該在代碼中添加一些錯誤處理,以確保查詢成功運行。 – andrewsi
您的查詢是否實際返回任何數據?在執行之前嘗試回顯查詢,檢查是否有錯誤,然後回顯$ result-> num_rows以檢查返回的內容。 – 2013-07-08 20:15:23