有很多与此相关的答案,但我找不到有用的信息。我试图连接到数据库并将用户输入的值插入到数据库中,但是我得到了这个错误,我真的不知道我做错了什么。我在两个不同的文件中创建了两个不同的类,一个是connection.php,另一个是users.php(用于将用户插入数据库)有人可以帮我解决这个问题吗?完整性约束违规:1048列'name'不能为空错误
这里是我的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'。) – David
但是我已经为它分配了一个变量$ _POST ['name'],它如何可以是空值?我不明白... – MKD
首先,在你的类中依赖'$ _POST'是一种糟糕的设计。该值应该在构造函数中需要,而不是假定存在于某些外部依赖项中。至于有一个空值,显然这个依赖没有你期望的那样。如果一个值不存在,它就是'null'。这就是'null'的意思。 – David