用于向数据库添加数据的PHP脚本不起作用

时间:2014-03-17 04:44:04

标签: php mysql database forms

我有一个php脚本将数据输入到表 listdata 中的数据库 list

以下是我的观点代码。

<form action="../add.php" method="post">

            <label for="title">Title:</label>
            <br>
            <input id="title" type="text" name="title"/>

            <br>

            <label for="body">Body:</label>
            <br>
            <textarea name="body" cols="30" rows="10"></textarea>

            <br>

            <input id="sb" type="submit" values="Add">
</form>

这是我的控制器(没有框架)

<?php
include 'config.php';
include 'views/add.view.php';

    if ($_SERVER['REQUEST_METHOD'] === 'post') {
            $conn = new PDO('mysql:host=localhost;dbname=list', $config['username'], $config['password']);
            $title = $_POST['title'];
            $body = $_POST['body'];
    if (empty($title) or empty($body)) {
        $status = "<h3>Enter Values</h3>";
        echo $status;
    } else {
        $stmt = $conn->prepare('INSERT INTO listdata(title,body) VALUES(:title,:body)');
        $stmt->bindParam(':title',$title);
        $stmt->bindParam(':body',$body);
        $stmt->execute();
        $status =  "<h3 message='id'>Added<h3>";
        echo $status;
    }



}



?>

当我在浏览器中运行它时,在发布值之前或之后,没有错误,但

$status
变量未被回显且数据库不存在更新。

1 个答案:

答案 0 :(得分:2)

尝试将您的控制器更改为:

<?php
include 'config.php';
include 'views/add.view.php';

    if ($_POST) {
        $conn = new PDO('mysql:host=localhost;dbname=list', $config['username'], $config['password']);
        $title = $_POST['title'];
        $body = $_POST['body'];
       if (empty($title) || empty($body))
       {
           $status = "<h3>Enter Values</h3>";
       }
       else
       {
           $stmt = $conn->prepare('INSERT INTO listdata(title, body) VALUES(:title, :body)');
           $stmt->execute(array(':title'=>$title, ':body'=>$body));
           $status =  "<h3 message='id'>Added<h3>";
       }
       echo $status;
}

?>