我在PHP / HTML / SQLITE3中工作。我有一个由几个表组成的数据库,其中一个表叫做Item,它包含itemID,item的名称等等。所以我的搜索接受了itemID的用户输入,我想要返回的是与该itemID相关的所有内容。
我已经测试了我的搜索,它确实返回了itemID,但是,我在查找如何返回与itemID相关的所有内容时遇到了一些麻烦。下面是我的搜索表单以及我对包含查询的单独文件的内容。
<form method="POST" action="action.php">
<input name="search" type="text" size="20" maxlength="10"/>
<input type="submit" value="Search"/>
</form>
<?php
if (isset($_POST["search"])) {
$itemID = $_POST["search"];
try {
$db->beginTransaction();
$query = "SELECT * FROM Item WHERE itemID = '$itemID';";
$result = $db->query($query);
if (empty($_POST['search'])){
echo "<strong>You didn't fill in anything!</strong>";
}
else {
echo $itemID;
}
$db->commit();
}
$db = null;
?>
编辑代码(添加对fetchall的尝试):
<?php
if (isset($_POST["search"])) {
$itemID = $_POST["search"];
try {
$db->beginTransaction();
$query = "SELECT * FROM Item WHERE itemID = '$itemID';";
#$result = $db->query($query);
$result = sqlite_fetch_all($query, SQLITE_ASSOC);
foreach($result as $entry) {
echo 'ItemID: ' . $entry['itemID'] . ' Item Name' . $entry['name'];
}
if (empty($_POST['search'])){
echo "<strong>Esteemed customer did not fill in a
itemID number, please search again. </strong>";
}
$db->commit();
}
第二次尝试:
<?php
$dbname = "mydatabase.db";
try {
// Establish connection to "mydatabase.db"
$db = new PDO("sqlite:" . $dbname);
// Set error handling so that errors throw an exception
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// Enable foreign key constraints on the database
$db->exec("PRAGMA foreign_keys = ON;");
} catch (PDOException $e) {
echo "SQLite connection failed: " . $e->getMessage();
exit();
}
if (isset($_POST["search"])) {
$itemID = $_POST["search"];
try {
$sth = $db->prepare("SELECT * FROM Item WHERE itemID = '$itemID'");
#$query = "SELECT * FROM Item WHERE itemID = '$itemID';";
#$result = $db->query($query);
$sth->execute();
$result = $sth->fetchAll();
print_r($result);
#if (empty($_POST['search'])){
#echo "<strong>Esteemed customer did not fill in a
#itemID number, please search again. </strong>";
}
}
?>
非常感谢任何输入。
答案 0 :(得分:0)
您应该将itemid连接到查询
$query = "SELECT * FROM Item WHERE itemID = '" . $itemID . "';";