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
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.
Got a question about inserting data (10 columns) in a table which has 30 columns. I've set all the default values at NULL and inserting like this:
INSERT INTO `app_res_per_form` VALUES ('monkey', 'bizon', 'Option one,Option two', '2', '1,2,3,4', 'charmender', 'dodo', 'bird')
Doesnt work because I get a Column Count doesnt match Row Count. I can only presume that is because I don't have 30 values but only 10. Or is it something different?
The table I want to insert it into has 1 Primary Key ID int(11) and the rest is TEXT columns which has a Default of NULL.
You need to specify the columns you want to insert to
INSERT INTO `app_res_per_form` (<col1>,<col2>,...) VALUES (<val1>,<val2>,...)
If the primary key is an auto increment then you do not need to include that column. If it is not auto increment then you do.
You still have to pass NULL in the query for the columns and specify ALL columns in the query
Good evening ..
I am posting a form with values that include the number of the column in the data base (and not it's name) , so i want to update the field that the column name refers to,
here is my code :
$hours=$_POST['hour'];
$date=$_POST['date'];
$s=$_POST['subject'];
$res=mysql_query("UPDATE study SET [$s] ='$hours' WHERE day='$date' ");
Where $s is an integer that equals the number of the wanted column. But it doesnt work . so is there a way to refer to a column by it's number rather than it's name ?
According to This question, it seems you can only do that by using the information_schema table.
Add an autoincrement column that carries the unique number of the row to an existing table
ALTER TABLE mytable ADD idnum INT NOT NULL AUTO_INCREMENT;
(or add the field in a new table
CREATE TABLE mytable (
idnum INT NOT NULL AUTO_INCREMENT,
... )
And set idnum as PRIMARY KEY.
So that all rows have a unique number created by MySQL automatically. To insert a row, set the field to null and MySQL sets the number automatically
INSERT INTO mytable (idnum, ...) VALUES (null, ...);
Note that you can retrieve the idnum that MySQL set automatically thanks to PHP APIs, eg for mysqli (see this page),
$lastid = $mysqli->insert_id(); // $mysqli being the mysqli object
Then to update a value, you have to store somewhere (preferably in the session rather than on the page [since the user can modify it in this case - unless it doesn't matter])
// Modify field form
...SELECT idnum,nhours FROM mytable WHERE thedate = ...
$_SESSION['idnum'] = $row['idnum'];
...
// Display form ...
// Form processing
// Check first if SESSION has an idnum (an other parameters) in case the user hacked the page and submit a "special" form ...
/// Then
$res=mysql_query("UPDATE study SET nhours='$hours' WHERE idnum=" . $_SESSION['idnum']);
First I have to create a column in the end of table
If there exist the data in the original column , move them into the new column
If the original column has no data now
(because they must be nullable , so that there is chance the column has no data, the column will be deleted)
The problems are:
move from col to new col is insert into new col {select old colmn from table} ?
Then how can I check the column exist no data / all col is null.
Also, How can I check datatype and whether it is null in pdo ?
Thank you
If you want to add a column to a table:
alter table myTable add column 'columnName' <column-specifications>
If you want to insert values from another column into this column:
update myTable set columnName=originalColumn
If you want to remove a column from a table:
alter table myTable drop column columnName
That being said, like Jeff Paquette mentioned, are you sure you want to create a new column? I don't really understand the point of creating a column to insert values from another column. Won't renaming your original column do the exact same thing?
alter table myTable change column ...