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
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.
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';
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]);
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.
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
Code
DB
This is the error I get when I try to add data in the db
The problem is in your table produs2: the id_produs field doesn't have the AUTO_INCREMENT attribute. Then, when you try to insert with id=null, no automatic numeric id is autogenerated.
To fix this, run this query in PHPMyAdmin:
ALTER TABLE `produs2` ADD `id_produs` INT NOT NULL AUTO_INCREMENT PRIMARY KEY
Make id_produs auto_increment and in line 76 in inserare.php neither include id_produs nor "null" in the insert statement because it is trying to insert null value to a primary key field.
I have an HTML form with an input field (type="date") and a mysql DB with a column with datatype "date" that accepts null when I do the query directly in phpmyadmin.
Also when I select a date in my html form (using browser default date picker) the query runs correctly. But when I leave the mentioned input blank, the following error is shown "Incorrect date value: '' for column 'received_date'.
Any help to get rid of this issue is appreciated.
Here are the sql and DB/Table schema:
CREATE TABLE customer.tbl1 ( id INT NOT NULL AUTO_INCREMENT , usrname
VARCHAR(32) NOT NULL , received_date DATE NULL DEFAULT NULL , PRIMARY
KEY (id)) ENGINE = MyISAM;
$sql = "INSERT INTO tbl1 (usrname, received_date) VALUES ('$usrname',
'$received_date')";
Thank you all.
The following solved the issue:
if (empty($received_date)) {
$received_date= 'NULL';
}
However, before posting the problem here I tried this (if condition) with NULL without the single quotes but It didn't work. Now the single quotes solved the issue.
The answer depends on your application: Is Null a valid value for your data?
If that's ok, then update your database schema to allow Null values (https://stackoverflow.com/a/35963275/3341745).
If you don't want this value to be Null, then the database check is doing its job. In this case, you should validate the data on the web page before the user is allowed to submit it (https://www.w3schools.com/js/js_validation.asp).
I'm trying to follow along to https://netbeans.org/kb/docs/javaee/ecommerce/connect-db.html this for an assignment but I'm using my own entity relationship diagram in mySQL workbench.
As can be seen here https://www.flickr.com/photos/93791690#N02/23076476850/in/dateposted-public/
But when I try and follow what is said on the Netbeans site Delete 'select * from category' and enter the following SQL statement:
INSERT INTO `category` (`name`)
VALUES ('dairy'),('meats'),('bakery'),('fruit & veg');
But try with my own:
INSERT INTO `book` (`price`) VALUES ('20.0');
INSERT INTO `book` (`author_name`) VALUES ('author_name');
I keep getting errors saying
Error code 1364, SQL state HY000: Field 'author_name' doesn't have a default value
Line 1, column 1
Error code 1364, SQL state HY000: Field 'price' doesn't have a default value
Line 2, column 1
Execution finished after 0 s, 2 error(s) occurred.
Can someone please help me to start going in the right direction
Unless you want to insert two lines,
INSERT INTO `book` (`price`, `author_name`) VALUES ('20.0', 'author_name');
is likely what you want to do. The inserts trying to set just one column are failing because the other column has no default value. All columns which do not have a default value need to be set in an insert. If you intended to insert two rows here, then you'll need to make sure you specify values for both columns in each insert or ALTER your table so that the column has DEFAULT values. For example,
ALTER TABLE `book` MODIFY `author_name` varchar(200) DEFAULT '';
changing the size of the varchar to be whatever your author_name column is and replacing the empty string '' with whatever you want the default to be.
as i see every where even in here :
From the MySQL manual:
If an ENUM column is declared to permit NULL, the NULL value is a
legal value for the column, and the default value is NULL. If an ENUM
column is declared NOT NULL, its default value is the first element of
the list of permitted values.
But in my database is not like this !!!! Why ?
this is one of field structure :
`dead` enum('0','1') NOT NULL DEFAULT '0';
but why all data in the dead field is null ???
and if i chose that type to enter a value this will be list :
()Empty
(0)
(1)
Why always null is there ?
and another thing is when i use query like this :
UPDATE TABLE SET dead = 0 -> result : dead = null
UPDATE TABLE SET dead = 1 -> result : dead = 0
UPDATE TABLE SET dead = 2 -> result : dead = 1
Best Regards.
It is not clear what you are asking for.
Here is fiddle: http://sqlfiddle.com/#!9/8b24d0/1
As we can see when dead is not set in INSERT query:
insert into table1 (id) values (4);
mysql put there your default value '0' and that is what you were expecting I guess.
I don't know what version of mysql do you use, but in my fiddle it is clear that mysql doesn't allow to:
UPDATE table1 SET dead = 0;
Since it is enum, it only allows:
UPDATE table1 SET dead = '0';
And that is correct and expected behavior since you choose ENUM type for the column. So I can't reproduce described in OP behavior. If anybody else can?
GUESS I guess that you are trying to convert existing table column with existing data in that column and stuck. So to run alter table you should fix data first like:
UPDATE table1 SET dead='0' WHERE dead IS NULL;
So once you get data fixed you can try ALTER TABLE to set DEFAULT.