2015-11-21 35 views
0

我正在使用PHP/HTML/SQLITE3。我有一個由多個表組成的數據庫,其中一個表稱爲Item,其中包含itemID,item的名稱等等。因此,我的搜索需要itemID的用戶輸入,我想返回的是與該itemID關聯的所有內容。PHP - 使用表單搜索並返回記錄

我測試了我的搜索,它確實返回了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>"; 
     } 
    } 

    ?> 

任何輸入將是不勝感激。

+2

看起來像你只需要 – billyonecan

+2

您還沒有執行它後做與查詢什麼來獲取'$ result'資源。做一個抓取。您也可以使用此代碼打開SQL注入。 – chris85

+0

啊,所以我應該用我的$結果替換:$ result = $ sth-> fetch(PDO :: FETCH_ASSOC);代替? 謝謝你讓我知道克里斯,這是一個小班的項目,所以它不會上線。 :-) – Yozuru

回答

0

你應該串聯條目標識到查詢

$query = "SELECT * FROM Item WHERE itemID = '" . $itemID . "';"; 
+2

爲什麼?雙引號字符串中的變量是插值的 – billyonecan

+0

@billyonecan我的不好,你是對的 – Mike