本文介绍了违反完整性约束:1048 列“名称"不能为空错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有很多与此相关的答案,但我找不到有用的信息.我正在尝试连接到数据库并将用户输入的值插入其中,但是我遇到了这个错误,我真的不知道我做错了什么.我在 2 个不同的文件中创建了 2 个不同的类,一个是 connection.php,另一个是 users.php(用于将用户插入数据库)有人可以帮我解决这个问题吗?

there were a lot of answers related to this, but I couldn't find useful information. I'm trying to connect to the database and insert user's entered values into it, but I got this error and I seriously don't know what I am doing wrong. I've created 2 different classes in 2 different files, one is connection.php and the other is users.php (for insterting the users into the database) Could someone help me to solve this?

这是我的 connection.php 文件:

Here is my connection.php file:

<?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 文件:

And here is my users.php file:

<?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 行收到此错误,即:

I got this error on users.php line 27, which is:

$stmt->execute();

它说:

致命错误:未捕获的 PDOException:SQLSTATE[23000]:违反完整性约束:1048 列名称"不能为空

我知道这里有很多代码,但如果有人愿意帮助我,谢谢...

I know here are a lot of code, but thanks if someone will try to help me...

推荐答案

错误似乎很清楚.表中有一列不能采用 NULL 值.

The error seems quite clear. You have a column in the table that cannot take on a NULL value.

我推测它不是您明确提供值的列之一(namesurnameemployment_date).您需要查看表的定义并查找另一列定义为 NOT NULL(或者可能没有默认值的 PRIMARY KEY).

I would speculate that it is not one of the column where you are explicitly providing a value (name, surname, employment_date). You need to look at the definition of the table and look for another column defined as NOT NULL (or perhaps PRIMARY KEY with no default value).

这篇关于违反完整性约束:1048 列“名称"不能为空错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-05 13:53