【发布时间】:2017-03-07 11:54:01
【问题描述】:
有很多与此相关的答案,但我找不到有用的信息。我正在尝试连接到数据库并将用户输入的值插入其中,但是我收到了这个错误,我真的不知道我做错了什么。我在 2 个不同的文件中创建了 2 个不同的类,一个是 connection.php,另一个是 users.php(用于将用户插入数据库)有人可以帮我解决这个问题吗?
这是我的 connection.php 文件:
<?php
class Connection {
public $dbh;
// Setting Database Source Name (DSN)
public function __construct() {
$dsn = 'mysql:host=localhost;dbname=employees';
// Setting options
$options = array (PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION);
// Making the connection to the database
try {
$this->dbh = new PDO($dsn, 'root', '', $options);
}
catch (PDOException $e) {
$this->error = $e->getMessage();
}
}
}
$connection = new connection();
?>
这是我的 users.php 文件:
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
include 'connection.php';
class Users {
public $name;
public $surname;
public $employmentDate;
public $connection;
public function __construct($connection)
{
$this->connection = $connection;
if(isset($_POST['Submit'])) {
$this->name = $_POST['name'];
$this->surname = $_POST['surname'];
$this->employmentDate = $_POST['employmentDate'];
}
}
// Inserting users values to the database table
public function insertUserValues() {
$query= 'INSERT INTO employee (name,surname,employment_date)
VALUES (:name,:surname,:employmentDate)';
$stmt = $this->connection->dbh->prepare($query);
$stmt->bindValue(':name',$this->name, PDO::PARAM_STR);
$stmt->bindValue(':surname',$this->surname, PDO::PARAM_STR);
$stmt->bindValue(':employmentDate',$this->employmentDate, PDO::PARAM_STR);
$stmt->execute();
}
}
$users = new Users($connection);
$users->insertUserValues();
?>
我在 users.php 第 27 行收到此错误,即:
$stmt->execute();
它说:
Fatal error: Uncaught PDOException: SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'name' cannot be null
我知道这里有很多代码,但是如果有人愿意帮助我,谢谢...
【问题讨论】:
-
您正在尝试将
null值插入到name列中,该列不允许空值。从列中删除该限制或为列提供值。 (看起来$this->name是null。) -
但是我已经为它分配了一个变量 $_POST['name'] ,它怎么可能是空值?我不明白...
-
一方面,在你的班级中对
$_POST的依赖是一种糟糕的设计。该值应该是构造函数所必需的,而不是假定存在于某些外部依赖项中。至于有一个空值,显然该依赖项没有您期望的那样。如果值不存在,则为null。这就是null的意思。