[英]Data retrival from SQL table using PHP & HTML5
我已經建立了一個玩具圖書館的網站,該網站使用HTML5,用於主頁的CSS3和用於維護服務器上數據庫的SQL。 在主頁上有兩種形式。 一種是租用可用的玩具,在添加數據時,會將實際數據添加到服務器上的SQL數據庫中。 問題是當我需要從SQL提取數據時,我在窗體上有四個下拉選項。 城市,玩具類型,年齡段和可用性。 用戶可以選擇4個選項的任意組合。 如果有匹配的玩具可用,則應顯示數據。
我有以下代碼
try
{
$dbh = new PDO("mysql:host=localhost; dbname=***", "***", "***");
}
catch (Exception $e)
{
die('<p style="color:red">Could not connect to DB: ' . $e->getMessage() . '</p></body></html>');
}
if (isset($_POST["ownercity"]))
{
$city = $_POST["ownercity"]; //Asker's preferable city
$command = "SELECT * FROM Toys WHERE City=?";
$stmt = $dbh->prepare($command);
$stmt->execute(array($city));
if (isset($_POST["ownertoytype"]))
{
$type = $_POST["ownertoytype"]; //Asker's preferable toy type
$command = "SELECT * FROM Toys WHERE City=? AND Type=?";
$stmt = $dbh->prepare($command);
$stmt->execute(array($city,$type));
if (isset($_POST["agegroup"]))
{
$goodage = $_POST["agegroup"]; //Asker's age group preference
$command = "SELECT * FROM Toys WHERE City=? AND Type=? AND Agegroup=?";
$stmt = $dbh->prepare($command);
$stmt->execute(array($city,$type,$goodage));
if (isset($_POST["ownerweek"]))
{
$availability = $_POST["ownerweek"];//Asker's preference for availability
$command = "SELECT * FROM Toys WHERE City=? AND Type=? AND Agegroup=? AND Availability=?";
$stmt = $dbh->prepare($command);
$stmt->execute(array($city,$type,$goodage,$availability));
}
}
}
}
$row1 = $stmt->fetch();
if($row1)
{
while($row1 = $stmt->fetch())
{
echo "<h2 id='general'>"."Congratulations! Matching toys are available, Contact owners directly!"."</h2>";
echo "<table class='toy' id='available'><tr><th>City</th><th>Type</th>
<th>Age Group</th><th>Name</th><th>Email</th><th>Phone</th>
</tr>";
echo "<tr><td>".($row1['City'])."</td>";
echo "<td>".($row1['Type'])."</td>";
echo "<td>".($row1['Agegroup'])."</td>";
echo "<td><b>".($row1['Name'])."</b></td>";
echo "<td><b>".($row1['Email'])."</b></td>";
echo "<td><b>".($row1['Phone'])."</b></td></tr>";
echo "</table>";
}
}
else
{
echo "<h2 id='general'>"."Sorry! No matching toys are available, please try again later"."</h2>";
}
現在,無論設置什么選項,即使有,也沒有匹配的玩具可用。
我的代碼有什么問題?
謝謝
您可能需要查找SQL的有效語法。
SELECT * FROM Toys WHERE City=?,Type=?,Agegroup=?
在這里,您假設逗號是有效的連詞。 不是。 有效的包括AND
和OR
。
如果要從“ Toys
中找到滿足一個或多個條件的行,請使用此查詢。
SELECT *
FROM Toys
WHERE (City=? OR Type=? OR Agegroup=?)
優良作法是將OR
子句序列括在括號中。
第一件事情,如奧利說,在查詢你必須使用AND
和OR
代替,
。 代碼本身也存在問題。 這些字段將始終被設置,因此您應該在if語句中檢查它們是否為空。
if (isset($_POST['fieldname']) && trim($_POST['fieldname']))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.