douzi8127
2015-06-17 21:07
浏览 78
已采纳

在html输入字段(PDO)中显示MySQL表数据

I want this form to load any data found in the "header" and "summary" columns in my database into the input fields for ease of editing. Then, after the user submits the form, the contents are dumped back into the DB and the new "values" are shown in the form. My issue is that the "dumping" part works fine, however when I refresh the page or navigate back to the form, no data is displayed and the data in the table has been replaced by white space...How do I fix this?

// Form 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 -->

// 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>
  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • dongshan7708 2015-06-17 21:14
    已采纳

    Assuming you're using the same script to display the form and process the submission, you need to check whether the form was submitted before updating the DB.

    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;
    }
    

    I've also shown how to use parameters in the prepared statement to prevent SQL injection.

    已采纳该答案
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题