【问题标题】:Unable to save form data to sql table using php无法使用php将表单数据保存到sql表
【发布时间】:2018-11-20 21:34:58
【问题描述】:

我正在尝试使用 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;

        }
}

?>

保存数据.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";
}


    }

}


?>

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

【问题讨论】:

  • 你曾经调用过这些方法吗?
  • @Barmar:no.这是我第一次使用它
  • 你只是定义了函数,你需要调用它们来执行代码。
  • @Barmar:感谢您提供详细信息。我添加了函数 connect() 以及像 $sql->connect()->execute(); 这样的执行。这是正确的方法吗?抱歉,我是 php 新手
  • 尝试将pdo报错设置为异常,以便查看是否有错误:$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

标签: php html mysql


【解决方案1】:

您应该在 var 中的 Savein 方法中调用“连接”方法。所以,你的 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";
}


}

【讨论】:

  • 运气不好
  • 还是不行?无论如何,你应该在 if 条件下只调用一次$sql-&gt;execute(),否则你的数据将被插入两次。我刚刚在我的答案中对其进行了编辑。
猜你喜欢
  • 2014-02-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-02-20
  • 2014-11-30
  • 1970-01-01
相关资源
最近更新 更多