OOP INSERT INTO声明无效

时间:2015-01-28 13:44:34

标签: php sql oop sql-insert

我正在创建一个非常简单的留言板来学习OOP风格的编程。目的是显示保存在数据库中的帖子,在显示的帖子下方,您可以向数据库添加新帖子,该帖子也将显示在页面上。

我在index.php页面上调用函数时遇到问题,所以当我点击提交时,它会将textarea中的内容添加到数据库中。有什么建议吗?

的index.php

<?php

ini_set("display_errors", 1);
error_reporting(E_ALL);

require_once("prikbord.class.php");

$p = new Prikbord();
$bericht = $p->getbericht();

if(isset($_POST['submit'])){
    $p->setbericht($_POST[$bericht]);
}
?>

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>Prikbord</title>
    </head>

    <body>
        <?php 
            echo $p->showdata();
        ?>

        <form action="" type="post">
            <textarea name="bericht" placeholder="Uw bericht" style="display: block; width: 350px; height: 150px;"></textarea>
            <input type="submit" name="submit" value="Submit">
        </form>
    </body>
</html>

Prikbord.class.php

<?php

class Prikbord {

    private $db;
    private $data = array();

    public function __construct() {
        $this->db = new mysqli("localhost", "root", "root", "prikbord");

        if($this->db->connect_error) {
            die("Fout met database verbinding.");
        }
    }

    public function getbericht() {
        $sql = "SELECT naam, datum, bericht FROM prikbord";

        $result = $this->db->query($sql);

        while($row = $result->fetch_assoc()) {
            $this->data[] = $row;
        }

        return $this->data;
    }

    public function showdata() {
        $return = "";

        foreach($this->data as $item) {
            $return .= "<div>" . $item["naam"] . "</div>";
            $return .= "<div>" . $item["datum"] . "</div>";
            $return .= "<div>" . $item["bericht"] . "</div>";
            $return .= "<hr style='width: 100px; float: left; display: inline;'>";
            $return .= "<br><br>";
        }

        return $return;
    }

    public function setbericht($bericht) {
        $sql = "INSERT INTO prikbord(bericht) VALUES ('" . $bericht . "')";

        $result = $this->db->query($sql);

        if($this->result) {
            echo "Data insert succesfully.";
        }
    }
}

?>

1 个答案:

答案 0 :(得分:0)

您根本不会发布您的数据。你应该打开你的表格:

<form name="myForm" method="POST">

注意:它是method,而不是type