无法使用php将表单数据保存到sql表

时间:2018-11-20 04:54:29

标签: php html mysql

我正在尝试使用php将表单数据保存到sql表中。尽管提交时我没有收到错误,但数据未显示在表中。

我的提交按钮名称为input_submit 这是我的代码:

if(isset($_POST['input_submit'])){

include 'dbConnection.php';
include 'saveData.php'; 

}

dbConnection.php

<?php

$path = $_SERVER['DOCUMENT_ROOT'];
include_once $path . '/wp-load.php';
include_once $path . '/wp-config.php';


class ConnectDB{

    private $servername;
    private $username;
    private $password;
    private $dbname;


    protected function connect(){

        $this->servername ="localhost";
        $this->username ="root";
        $this->password ="";
        $this->dbname ="testdb";

        $conn = new mysqli($this->servername,$this->username,$this->password,$this->dbname);

            if($conn -> connect_error) {

                die("connection failed:".$conn-> connect_error);
            }

        return $conn;

        }
}

?>

saveData.php:

<?php

    class saveinput extends ConnectDB {

    public function Savein(){

$date       = $_POST['date'];   
$entry_type = $_POST['entry_type'];
$amount     = $_POST['amount'];

    $sql = $conn->prepare("INSERT INTO wp_myexpenses (date, entry_type, amount) 
    VALUES(?, ?, ?)");

$sql->bind_param("sss",$date, $entry_type, $amount);

$sql->execute();

if ($sql->execute()) { 
  echo "success";
} else {
  echo "failed";
}


    }

}


?>

提交时,表单正在提交。但是当我检查数据库表时,什么都没有显示。我不明白这里出了什么问题。有人可以指导我吗。

1 个答案:

答案 0 :(得分:0)

您应该在var中的Savein方法内调用“ connect”方法。因此,您的Savein方法应为:

public function Savein(){
$conn = parent::connect(); // This is the only thing i've added

$date       = $_POST['date'];   
$entry_type = $_POST['entry_type'];
$amount     = $_POST['amount'];

    $sql = $conn->prepare("INSERT INTO wp_myexpenses (date, entry_type, amount) 
    VALUES(?, ?, ?)");

$sql->bind_param("sss",$date, $entry_type, $amount);

if ($sql->execute()) { 
  echo "success";
} else {
  echo "failed";
}


}