我一直在尝试使用prepare(),bindParam()和execute()函数来实现PDO,以允许根据用户输入的数据构建查询。
我想显示图书清单,然后允许用户过滤列表,然后查看新列表和完整列表。
当我在表格中输入标准时,搜索没有任何反应。我在俯瞰什么?
这是代码
<?php
$pageTitle = "Book List";
$pageHeading = "Book List";
include_once ('header.php');
include_once('databaseConnection.php');
if(isset($_POST['txtSearchBookTitle'])) {
$db = new DatabaseConnection();
$db = $db->db_connection;
$searchTitle = ($_POST['txtSearchBookTitle']);
$sql = $db->prepare("SELECT title FROM tblBook WHERE title LIKE ('%:searchTitle%') ORDER BY title");
$sql->bindParam(':searchTitle', $searchTitle);
$sql->execute();
$result = $sql->fetchAll();
print_r($result);
foreach ($result as $row) {
echo "<li>" . " " . $row["title"]. " " . "</li>";
}
}
?>
<form name="searchBookTitle" method="post" action="<?php echo htmlentities($_SERVER['PHP_SELF']);?>" >
<fieldset>
<legend>Search Books</legend>
<label for="txtSearchBookTitle">Search by Book Title</label>
<input type="text" name="txtSearchBookTitle" id="txtSearchBookTitle">
<input type="submit" value="Submit">
</fieldset>
</form>
<?php
include_once('getBooks.php');
getBooks();
include 'footer.php';
?>
答案 0 :(得分:1)
您需要以这种方式准备输入:
$searchTitle = $_POST['txtSearchBookTitle'];
$sql = $db->prepare("SELECT title FROM tblBook WHERE title LIKE :searchTitle ORDER BY title");
$sql->execute(array(':searchTitle' => '%' . $searchTitle . '%'));
或者像这样:
$searchTitle = $_POST['txtSearchBookTitle'];
$sql->bindParam(':searchTitle', "%{$searchTitle}%");
答案 1 :(得分:-1)
在fetchAll中使用PDO::FETCH_ASSOC
..这意味着它会将数据作为数组返回
所以就像这个一样
$result = $sql->fetchAll(PDO::FETCH_ASSOC);