我正在爲MySQL數據庫做一個PHP前端。我有一個名爲「Regions」的表,其中包含RegionID(int),Name(字符串)和Country(字符串)。我試圖將一個<選擇>列表到包含所有區域作爲選項的表單上,使用<optgroup>的按國家分組地區。我已經通過嵌套的普通查詢成功地完成了它,現在我正在努力讓自己的頭腦準備好準備好的語句。'無效的對象或資源'與bind_param
到目前爲止,我已經得到了什麼是:
// $DB is database object, already connected
// Error checking will be worked into this once I've worked out the basics...
$stmt_country = $DB->stmt_init();
$stmt_country->prepare("SELECT DISTINCT Country FROM Regions ORDER BY Country ASC");
$stmt_country->execute();
$stmt_country->bind_result($CountryName);
$stmt_region = $DB->stmt_init();
$stmt_region->prepare("SELECT RegionID,Name FROM REGIONS WHERE Country=? ORDER BY Name ASC");
$stmt_region->bind_param("s",$CountryName);
echo "<select name=\"RegionID\">\n";
while ($stmt_country->fetch()) {
// Start 'country' option group
echo "<optgroup label=\"$CountryName\">\n";
// Execute the 'regions' query using the 'country' parameter
$stmt_region->execute();
$stmt_region->bind_result($RegionID,$RegionName);
while ($stmt_region->fetch()) {
// Output the regions matching that country
echo "<option value=\"$RegionID\">$RegionName</option>\n";
}
echo "</optgroup>\n";
}
echo "</select>\n";
然而,當我運行此我得到:
Warning: mysqli_stmt::bind_param(): invalid object or resource
在
$stmt_region->bind_param("s",$CountryName)
線
。
隨着一些註釋掉的代碼,我的工作(即產出只是optgroups每個國家),然後在$CountryName
值bodging得到的只是它的一半$stmt_country
的$stmt_region
一半它的工作原理本身,但我無法讓兩個人一起工作。有人可以告訴我哪裏出錯了嗎?
出於興趣,如果跳過'stmt_init()'調用並執行'$ stmt_region = $ DB-> prepare(「SELECT ...」);'? – DaveRandom
您可以添加一些調試'print'語句來顯示'$ CountryName'的值在第二個查詢中依賴於它之前是否已正確設置? – sarnold
@DaveRandom - 我也想過。我通過複製我發現的示例和教程來學習,一些使用stmt_init(),一些則不使用。如果我調用stmt_init或不是有什麼區別? – Iain