2015-06-17 73 views
0

我希望此表單能夠將我的數據庫中「標題」和「摘要」列中找到的任何數據加載到輸入字段中,以便於編輯。然後,在用戶提交表單後,內容將被轉儲回數據庫,並在窗體中顯示新的「值」。我的問題是,「傾銷」部分工作正常,但是當我刷新頁面或導航回表單時,沒有數據顯示,表中的數據已被空白空間替換...我該如何解決這個問題?在html輸入字段(PDO)中顯示MySQL表格數據

//形式PHP

<!-- Process POST Data and dump into DB --> 
<?php 

    $header1 = $_POST['header1']; 
    $summary1 = $_POST['summary1']; 

    $handler = new PDO('mysql:host=localhost;dbname=myDB', 'username', 'password'); 
    $handler->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); 

    $sql = "UPDATE myTable SET header='$header1', summary='$summary1' WHERE id=1"; 

    try { 

     $stmt = $handler->prepare($sql); 

     $stmt->execute(); 

    } catch(PDOException $e) { 
     echo $e->getMessage(); 
     die(); 
    } 

    $handler = null; 
?> 
<!-- Get mysql data --> 
<?php 
    $handler = new PDO('mysql:host=localhost;dbname=myDB', 'username', 'password'); 
    $handler->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); 

    $fetchData = $handler->prepare("SELECT * FROM newsletters WHERE id=1"); 
    $fetchData->execute(); 

    $data = $fetchData->fetchAll(); 
?> 

<!-- form --> 

// HTML表單

<form action="index.php" method="POST"> 
<input type="text" name="header1" value="<?php foreach ($data as $Data){echo $Data['header'];} ?>"> 
<textarea name="summary1" rows="5" value="<?php foreach ($data as $Data){echo $Data['summary'];} ?>"></textarea> 
<input type="submit" name="submit1" value="Submit"> 
</form> 
+0

'index.php'也是顯示錶單的腳本嗎? – Barmar

+0

你很容易遭受[sql注入攻擊](http://bobby-tables.com)。 –

+0

'index.php'顯示錶單,是的。 – htmlboss

回答

0

假設你正在使用相同的腳本來顯示錶單和處理提交,則需要檢查是否形式在更新數據庫之前已提交。

if (isset($_POST['header1'], $_POST['summary1'])) { 
    $header1 = $_POST['header1']; 
    $summary1 = $_POST['summary1']; 

    $handler = new PDO('mysql:host=localhost;dbname=myDB', 'username', 'password'); 
    $handler->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); 

    $sql = "UPDATE myTable SET header= :header , summary= :summary WHERE id=1"; 

    try { 

     $stmt = $handler->prepare($sql); 
     $stmt->execute(array(':header' => $header1, ':summary' => $summary1)); 

    } catch(PDOException $e) { 
     echo $e->getMessage(); 
     die(); 
    } 

    $handler = null; 
} 

我還展示瞭如何在準備語句中使用參數來防止SQL注入。

+0

非常感謝您的參數! – htmlboss

相關問題