【发布时间】: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);