如何使用PHP搜索包含多个单词的值的数据库?
我正在从事PHP课程中的一个项目,我必须使用SQLite为博物馆及其所在国家创建一个数据库,从网页(使用PHP/HTML)连接到该数据库,并根据从下拉列表中选择的国家生成博物馆列表。我遇到的问题是,我似乎无法从多个单词(美国、英国等)的国家值返回数据。它在单词国家非常有效。生成的预选列表包含正确的信息,但未正确生成选择列表 以下是一个数据库示例(SQLite): 以下是PHP/HTML代码:如何使用PHP搜索包含多个单词的值的数据库?,php,html,sql,database,sqlite,Php,Html,Sql,Database,Sqlite,我正在从事PHP课程中的一个项目,我必须使用SQLite为博物馆及其所在国家创建一个数据库,从网页(使用PHP/HTML)连接到该数据库,并根据从下拉列表中选择的国家生成博物馆列表。我遇到的问题是,我似乎无法从多个单词(美国、英国等)的国家值返回数据。它在单词国家非常有效。生成的预选列表包含正确的信息,但未正确生成选择列表 以下是一个数据库示例(SQLite): 以下是PHP/HTML代码: <?php $museumDb = new PDO('sqlite:museum.sql
<?php
$museumDb = new PDO('sqlite:museum.sqlite');
$query = $museumDb->prepare('SELECT * FROM museums');
$query->execute();
$museums = $query->fetchAll(PDO::FETCH_ASSOC);
$country = $museumDb->prepare('SELECT DISTINCT country FROM museums ORDER BY country ASC');
$country->execute();
$countryLists = $country->fetchAll(PDO::FETCH_ASSOC);
?>
<form method="POST"> //selection form
<fieldset>
<legend><strong>Select from the drop down list below to narrow your search results by country</strong></legend>
<select name="country" id="country">
<?php foreach($countryLists as $countryList): ?>
<!--Generates drop down list of countries from DB-issue may be here?-->
<option value=<?php print $countryList['country']; ?>><?php print $countryList['country']; ?></option>
<?php endforeach; ?>
</select>
<input type="submit" name="submit" value="Submit">
</fieldset>
</form>
<?php if (isset($_POST) && !empty($_POST)) {
$countryName = htmlspecialchars($_POST['country']); //retrieves POST data from form selection
print $countryName; //testing
$new = $museumDb->prepare("SELECT country, museum_name FROM museums WHERE country = '$countryName'"); //sqlite query setting country = selected country from form
$new->execute();
$newLists = $new->fetchAll(PDO::FETCH_ASSOC);
print '<pre><code>';
while ($row = $new->fetch(PDO::FETCH_ASSOC)) {//testing
var_dump($row);
}
var_dump($newLists); //testing query
var_dump($new); //testing
print '</code></pre>';
?>
<table><!--table not generating for countries with two words in name-->
<tr>
<th>Museum Name</th>
<th>Country</th>
</tr>
<?php foreach ($newLists as $newList): ?>
<tr>
<td><?php print $newList['museum_name']; ?></td>
<td><?php print $newList['country']; ?></td>
</tr>
<?php endforeach; ?>
</table>
';
?>
博物馆名称
国家
我不确定如何将此问题标记为已回答,但一条评论给了我需要更改的信息,这是一个非常简单的修复方法 原始行:
<option value="<?php print $countryList['country']; ?>"><?php print $countryList['country']; ?></option>
固定电话:
谢谢
htmlspecialchars
将空间转换为与DB值不匹配的HTML实体。相反,您应该使用参数化查询。它们实际上很容易实现,对您来说应该只有2行或3行更改。使用引号表示值:I可能是错误的re:htmlspecialchars
。看起来它不会变换空间。但是建议是:参数化查询仍然有效,谢谢!这是一个我会花上几个小时来解决的问题,只是为了找到一个简单的解决办法。@Waterlomatt谢谢,我一定会研究参数化查询来了解它们的全部内容。看来布罗姆比尔的建议为我解决了这个问题
<option value=<?php print $countryList['country']; ?>><?php print $countryList['country']; ?></option>
<option value="<?php print $countryList['country']; ?>"><?php print $countryList['country']; ?></option>