So I have a PHP form to add a row to a database. If any of the unrequired fields are empty, the default value for that field should be used.
I tried to implement this with MySQLi like this:
$required = $_POST["required"];
$unrequired = isset($_POST["unrequired"])?$_POST["unrequired"]:"DEFAULT(`Unrequired`)";
$sql = $mysqli->prepare("INSERT INTO `table` (`Required`,`Unrequired`) VALUES (?,?)");
$sql->bind_param("is",$required,$unrequired);
$sql->execute();
But when I try to get the value of the unrequired field using SELECT unrequired FROM table WHERE required = 33, I get DEFAULT(`Unrequired`) instead of the default value of the column for varchar columns, and 0 for int and double columns.
Is this problem caused by PHP, or MySQL?
NOTE: Some of the unrequired fields are nullable and some are not. Those which aren't nullable have a set default value. int and double fields' set default value is 1, the rest are nullable.
Can't you just set default value in your database structure. Below you can see an example;
CREATE TABLE example_table
(
P_Id int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255) NOT NULL,
Address varchar(255), DEFAULT 'unrequired'
City varchar(255) DEFAULT 'Unrequired'
)
When you create your table like that you are good to go. You can also alter your table
ALTER TABLE example_table
ALTER City SET DEFAULT 'Unrequired'
Alright, I think I figured out the problem.
Since I am using prepared statements, every parameter that I put in the reslting SQL query statement will be converted into safe strings, ints or doubles, so I suppose expressions like DEFAULT(column) will be re-interpreted as "DEFAULT(column)", and will be considered as strings.
Although not a very safe solution, I've considered using not prepared statements, that is concat every parameter and using DEFAULT like in here. To make the queries safer, I'll use real_escape_string() for strings.
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'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.
I started to a new php script, and I used for the first time the DATATIME option in mysql. I think it makes the problem.
My sql table is :
id int(6) auto_increment,
name varchar(40) not null,
pseudo varchar(40) not null,
email varchar(40) not null,
password varchar(40) not null,
plan varchar(40) not null,
date DATETIME DEFAULT CURRENT_TIMESTAMP,
points int(6) not null,
primary key(id,name,pseudo,email,password,date,points,plan)
When I try to execute this query:
insert into users(NULL,"name","pseudo","email#email.com","Pass1919",NULL,
"100");
This error displays :
ERROR 1064 (42000): You have an error in your SQL syntax; check the
manual that corresponds to your MySQL server version for the right
syntax to use near 'NULL,
"name","pseudo","email#email.com","Pass1919",NULL,"100")' at line 1
try this..
insert into users(name,pseudo,email,password,paln,date,poits)
values("name","pseudo","email#email.com","Pass1919",NULL, "100");
As others have said, and
insert into users(name,pseudo,email,password,paln,date,poits)
values("name","pseudo","email#email.com","Pass1919",'', NULL, "100");
plan varchar(40) not null,
What they missed is plan is not null, and either enter null for date or I would prefer to just omit it completely.
insert into users(name,pseudo,email,password,paln,poits)
values("name","pseudo","email#email.com","Pass1919",'', "100");
If you count the fields and the inputs in some of the above responses they are not equal. The field list is optional in the insert but i would use them, for readability and to make sure you have the order and number of inputs correct.
Last thing change to the primary key, to just the auto increment field, if you need other compound indexes, you should add them separate and make unique as your requirements would require. Primary keys should be a surrogate key, as defined this way
the value is unique system-wide, hence never reused
the value is system generated
the value is not manipulable by the user or application
the value contains no semantic meaning
the value is not visible to the user or application
the value is not composed of several values from different domains.
The other keys should relate to the data, and like i said if you need a compound unique key, or just a unique filed like email make it separate from the primary one.
You have to use the keyword values:
insert into users values(NULL,"name","pseudo","email#email.com","Pass1919",NULL,
"100");
Don't pass first parameter as NULL, as you already specified it as primary key and auto increment also.
use this
insert into users values("name","pseudo","email#email.com","Pass1919",NULL, "100");
Try this
INSERT INTO users(
`name`,
`pseudo`,
`email`,
`password`,
`plan`,
`points`
)
VALUES (
NULL,
'name',
'pseudo',
'email#email.com',
'Pass1919',
NULL,
'100');
try to add your table field name which you want to insert values with values keyword. also auto increment id can not be NULL if you dont want to send id, date
values leave that it both will collect values auto with increment and current timestamp
insert into users(name,pseudo,email,password,plan,points) values ('name','pseudo','email#email.com','Pass1919','','100');
Also, when you are dealing with integers you do not need to enclose it in quotations when inserting so you can do
insert into users(name,pseudo,email,password,plan,date,points)
values("name","pseudo","joe.bloggs#mydomain.com","S3CuR3", "PLAN", "2014-06-26", 100);
Hi i am importing a csv through a script
the table structure is as below
`contact_id` int(11) NOT NULL auto_increment,
`contact_first` varchar(255) character set latin1 default NULL,
`contact_last` varchar(255) character set latin1 default NULL,
`contact_email` varchar(255) character set latin1 default NULL,
PRIMARY KEY (`contact_id`)
and the data in csv is like this
Jim,Smith,jim#tester.com
Joe,Tester,joe#tester.com
and the query i am using for insert is as below
mysql_query("INSERT IGNORE INTO contacts (contact_first, contact_last, contact_email) VALUES
(
'".addslashes($data[0])."',
'".addslashes($data[1])."',
'".addslashes($data[2])."'
)
");
i have made use of ignore function in the query but it doesnot work and it keeep on onserting the same value
The IGNORE keyword will only have your desired impact on duplicate rows.
A row will only be recognized as a duplicate if you have a primary key or unique key on the appropriate columns.
You haven't really explained exactly what the issue is, but I suspect you might want to create a unique key on the contact_email column to prevent duplicates from being inserted.
I would also suggest at a minimum using mysql_escape_string instead of addslashes to ensure the strings are encoded correctly.
There will likely be comments on the fact that the mysql_* functions are deprecated so you should look into PDO or mysqli_* functions.
If you use the IGNORE keyword, errors that occur while executing the INSERT statement are treated as warnings instead
Refer DOCS
The use of IGNORE is :
If you use the IGNORE keyword, errors that occur while executing the INSERT statement are treated as warnings instead. For example, without IGNORE, a row that duplicates an existing UNIQUE index or PRIMARY KEY value in the table causes a duplicate-key error and the statement is aborted. With IGNORE, the row still is not inserted, but no error is issued.
in your case you are inserting three values which are same but as the ID is auto incremental which will insert new record with same values which is obvious.
If you want to prevent it from inserting in to the database you have to add unique index to one of the other column
hope it will help!
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.