Home > Enterprise >  PHP - Can't insert into mySQL (structure db problem?)
PHP - Can't insert into mySQL (structure db problem?)

Time:02-21

I have a problem inserting data into my MySQL database. The structure of the db looks like this:

id | name | class |  23-02-2022 | 26-02-2022 | and so on ...

The databse is part of an attendance system. So I use dates as column names.

I use this code to open a csv file and upload some data into the db. As you can see in this part of the code I only put datas in the name and class column.

if (($handle = fopen("class.csv", "r")) !== FALSE)
{
    while (($data = fgetcsv($handle, 1000, ";")) !== FALSE)
    {
      
        $query="INSERT INTO table21228 (name, class) VALUES ('$data[0]' , '$data[1]')";
        if ($conn->query($query) === TRUE) {
        }
        else {
        echo 'Error: '. $conn->error;
        } fclose($handle);
     }

I get this error message: Error: Field '23-02-2022' doesn't have a default value

When I use a different table, where the only columns are id, name, class it works without any problems. So I guess the structure of my db must be the problem

Maybe all those dates columns like 23-02-2022???

Hope some might help me. Thank you!

Kind regards Dan

CodePudding user response:

The problem is that the columns of the dates dont have a DEFAULT value and since while adding a record you dont define a value for the column it is giving an error. The solution is that either you give a value for the columns while adding the records or else alter the columns and give it a default value.

But your Table structure is not at all feasible to use. You should not have columns for individual dates. Like this you will have infinite columns in your table. So instead the solution is that you insert the date of the attendance marked with the rows you add.

CodePudding user response:

Could be you have a table with not null columns and you try to insert a row without a proper value for the not nullable columns .. the you have the message for field '23-02-2022' doesn't have a default value

the try insert a proper value for these columns

$query="INSERT INTO table21228 (name, class, `23-02-2022`, `26-02-2022` ) VALUES ('$data[0]' , '$data[1]', '2022-02-20', '2022-02-20')";

or try revoke the not null constranits for theese columns

alter table table21228  modify column `23-02-2022` date;

or set a default value

ALTER TABLE table21228 MODIFY column `23-02-2022` date DEFAULT '2022-02-20';

CodePudding user response:

The problem is, that you try to insert a row into a table where not all columns do have a default value. You either need to give all columns a default value (using ALTER TABLE or a modified CREATE TABLE) or you have to mention all those columns in your INSERT query.

Also, your code is vulnerable to SQL injection. Read this great guide on how to prevent that: https://phpdelusions.net/pdo

If your table looks like this:

CREATE TABLE `attendances` (
 `id` INT NOT NULL AUTO_INCREMENT,
 `name` VARCHAR(250) NOT NULL,
 `class` VARCHAR(250) NOT NULL,
 `23-02-2022` INT NOT NULL,
 `26-02-2022` INT NOT NULL,
PRIMARY KEY (`id`)) ENGINE = InnoDB;

You can change it like this:

ALTER TABLE `attendances`
 CHANGE `23-02-2022` `23-02-2022` INT NULL DEFAULT NULL; 

or

ALTER TABLE `attendances`
 CHANGE `26-02-2022` `26-02-2022` INT NOT NULL DEFAULT '0'; 

Here, 23-02-2022 has a default value of "NULL" and 26-02-2022 is an example with a default value of "0". Or just create the table correctly in the first place:

CREATE TABLE `attendances` (
 `id` INT NOT NULL AUTO_INCREMENT,
 `name` VARCHAR NOT NULL,
 `class` VARCHAR NOT NULL,
 `23-02-2022` INT NULL DEFAULT NULL,
 `26-02-2022` INT NOT NULL DEFAULT '0',
PRIMARY KEY (`id`)) ENGINE = InnoDB; 

As an alternative, you could just add all columns that have no default value to your INSERT query:

INSERT INTO `attendances` (
 `id`, `name`, `class`, `23-02-2022`, `26-02-2022`
) VALUES (
 NULL, 'name1', 'class1', '0', '0'
);

Make sure to protect your app from SQL injection:

<?php
$pdo->prepare("
 INSERT INTO `attendances` (
   `id`, `name`, `class`, `23-02-2022`, `26-02-2022`
  ) VALUES (
   NULL, ?,?,?,?
 )
")->execute(['name1', 'class1', 0, 0]);

CodePudding user response:

So I use dates as column names.

...bad idea, because you theoretically have an infinite number of columns, if the system is used long term. And it will make it very difficult to write certain types of query to understand the data.

So I guess the structure of my db must be the problem

...essentially, yes.

To understand how to design your database correctly, you should learn about database normalisation.

In this scenario I'd suggest you'd have one table for the list of all people, and another for the list of all classes.

If you're running a predetermined timetable, you might then have a table which lists the class, the date and the teacher assigned to that date & class. (Or you might assign the teacher in the classes table, if one teacher normally takes the whole class.)

Then lastly you'd have a separate "attendance" table which contains columns "personID" and "attendanceDate", and "classID".

That way you will end up with multiple rows in there with the same person / class combination and different dates, to record all their attendances at each class and each date of that class. And it's completely extendable, infinitely, without you needing to modify the tables each time a new class or date is announced, or needing to dervice column names in your code when trying to generate a query.

CodePudding user response:

first check your csv file has the right amount of columns as your database then set your columns default to from not NULL to null or none

  • Related