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.
Related
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 have 2 similar tables. One with an auto increment value and one without. The first table first column is defined as INT(11), PRIMARY UNIQUE INDEX and under EXTRA in phpmyadmin it says AUTO_INCREMENT.
This code does not work and does not add any values.
mysqli_query($con, "INSERT INTO testtable1 VALUES ('', 'zzz', 'yyy')") ;
The second table is the same table with the first column dropped. This code works.
mysqli_query($con, "INSERT INTO testtable2 VALUES ('jjj', 'fff')") ;
Any idea what I am missing? Running 7.2 on the database.
Presumably your testtable1 has a definition reasonably similar to (pseudo-notation):
testtable1
------------
ID INT PK AUTOINCREMENT
SomeColumn NVARCHAR
AnotherColumn NVARCHAR
So when you do this:
INSERT INTO testtable1 VALUES ('', 'zzz', 'yyy')
You're explicitly telling the database to insert an empty string into an INT column. Which won't work.
An AUTOINCREMENT column doesn't need to be told there's an empty value, it will automatically increment. Just specify the values that you are inserting:
INSERT INTO testtable1 (SomeColumn, AnotherColumn) VALUES ('zzz', 'yyy')
Let the database engine handle the ID column. In general it's pretty much always worth explicitly specifying the columns into which you are inserting values or from which you are selecting values. It makes the code easier to read/support and reduces the chance of bugs/errors if the table definition ever slightly changes.
If I am reading this correctly, the first table has an int(11) with AUTO_INCREMENT.
This means you should use similar query as in table 2. As in only pass in values for the two non auto increments fields.
mysqli_query($con, "INSERT INTO testtable1 VALUES ('zzz', 'yyy')") ;
This will work as long as there are 3 fields, the first one is an auto inc int and the other two are strings. This is because auto inc handles the first column automatically.
Also, please check out this link or search for php MySQL predated statements to use prepared statements instead for some safety. It will help you against sql injections.
A db table consists of 3 columns. But I want to insert a value to one column and I want the other 2 to remain empty. Like database has three input column- roll, date, time, I want only to insert roll. My query:
insert into tableName(roll) values ('$_POST['roll'])
But I am getting the error message ( Field attn_time doesn't have a default value41 ). What would be the correct query?enter image description here
database table
You need to alter your database table by giving a default value to your attn_time column.
Example:
ALTER TABLE table_name MODIFY COLUMN column_name VARCHAR(255) NOT NULL DEFAULT '';
You achieve this in two ways:
1) Go to your phpmyadmin/mysql and change your columns(attn, attn_time) "Null" property to "Yes". This will allow null value to store in column if non value given.
[You can find "Change" in "Structure" tab in phpmyadmin]
2) You can change your query to
insert into tbl1 (roll, attn, attn_time) values ('$roll', null, null)
OR
insert into tbl1 (roll, attn, attn_time) values ('$roll', '', '')
You can use :
$roll=$_POST['roll'];
add your validation :
insert into tableName(roll) values ('$roll');
How can i prevent inserting a value into database if it is already exist with the same name in it? echoing alert that this name already exist
for example DATABASE has [MARY, MIKE, JOHN] and then someone tried to INSERT the name [JOHN] again, I want to prevent that from happening, Even if he changed the letter style [JoHn]
Add a UNIQUE index on the column(s) and make sure the column has a case-insensitive (preferably accent-insensitive too) collation. That should do it, I think.
If you try to SELECT first and see if the name is there, you can run afoul of a "race condition". Basically there's a small amount of time between you running the SELECT and INSERT, and someone else can manage to INSERT the name during that. It's a small chance, but it's there, and eventually it will bite you. You can counteract this with a transaction (be careful about the isolation level your transaction uses), but why bother when an index is so much simpler and easier? Also, you'll need an index on that column anyway if you want your check to be fast.
When defining a table UNIQUE may be specified for a given column so a duplicate entry attempt will result in an error (the INSERT query will fail).
For example:
CREATE TABLE `test` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`name` varchar(255) NOT NULL UNIQUE,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=UTF8;
Normally default collation for a varchar is case insensitive (checking would not be bad however).
Another option is to first execute a SELECT query to find if a record with the same field value already exists and then perform a second INSERT query if no rows are found or display an error otherwise
You could also use a trigger:
DELIMITER $$
CREATE TRIGGER if_exists BEFORE INSERT ON table_name
FOR EACH ROW
BEGIN
IF EXISTS(SELECT name FROM table_name WHERE LOWER(name) = LOWER(NEW.name)) THEN
SIGNAL sqlstate '45000' SET message_text = 'Error! User already exists.';
END IF;
END$$
DELIMITER ;
Replace table_name with the name of your table and name with the name of the attribute you want to compare.
Signals are supported by MySQL 5.5 and above.
Before insertion, select from table where username LIKE username
What I'm asking is whether when inserting a row in a MySQL database the columns that are null need to be included. For instance, when I use phpMyAdmin to insert a row, it will do something like this:
INSERT INTO table
(
`col1`,
`col2`,
`col3`,
`col4`
)
VALUES
(
'value1',
NULL,
NULL,
'value2'
)
Assuming the fields are null by default, can I remove columns and NULL values from the insert statement?
by default, when you create column it is nullable (unless you have set NOT NULL on it). so when you want to insert record for specific columns only, you can omit that column and the values for it are automatically null.
INSERT INTO table (`col1` ,`col4`)
VALUES ('value1','value2')
you can remove them.
if there is a default value - you will get that instead.
If the column name is also omitted, yes: the default value1 will be assumed.
1 NULL is usually - but not always! - the default value for nullable columns. The schema must be consulted to verify this assumption.