Error in SQL syntax DATATIME option - php

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);

Related

Is it possible to execute a multi-line SQL statment using PHP and Sqlite3 [duplicate]

I am trying to create a database using python to execute the SQL commands (for CS50x problem set 7).
I have created a table with an id field set to AUTO_INCREMENT, but the field in the database is populated only by NULL values. I just want it to have an incrementing id starting at 1.
I've tried searching online to see if I'm using the right syntax and can't find anything obvious, nor can I find someone else with a similar problem, so any help would be much appreciated.
Here is the SQL command I am running:
# For creating the table
db.execute("""
CREATE TABLE students (
id INTEGER AUTO_INCREMENT PRIMARY KEY,
first_name VARCHAR(255) NOT NULL,
middle_name VARCHAR(255) DEFAULT (NULL),
last_name VARCHAR(255) NOT NULL,
house VARCHAR(10),
birth INTEGER
);
""")
# An example insert statement
db.execute("""
INSERT INTO students (
first_name,
middle_name,
last_name,
house,
birth
)
VALUES (
?, ?, ?, ?, ?
);
""", "Harry", "James", "Potter", "Gryffindor", 1980)
Here is a screenshot of the database schema shown in phpliteadmin :
And here is a screenshot of the resulting database:
My guess is that you are using SQLite with phpliteadmin and not MySql, in which case this:
id INTEGER AUTO_INCREMENT PRIMARY KEY
is not the correct definition of the auto increment primary key.
In fact, the data type of this column is set to INTEGER AUTO_INCREMENT, as you can see in phpliteadmin, which according to 3.1. Determination Of Column Affinity, has INTEGER affinity.
Nevertheless it is the PRIMARY KEY of the table but this allows NULL values.
The correct syntax to have an integer primary key is this:
id INTEGER PRIMARY KEY AUTOINCREMENT
This cannot happen, if your statements are executed correctly.
I notice that you are not checking for errors in your code. You should be doing that!
My guess is that the table is already created without the auto_increment attribute. The create table is generating an error and you are inserting into the older version.
You can fix this by dropping the table before you create it. You should also modify the code to check for errors.

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

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

PHP | Mysql how to stop from inserting if any record with same id overdate exist

Well, I have this attendance system who mark an attendance every day, well what I am looking is for a restriction other than PHP code like a restriction that can restrict users to enter duplicate record over time.
For e.g I have already marked my attendance .myself
DATE 22-05-2018 and trackingid = 1
if I try to insert mark attendance one more time it should not insert the statement.
It can be done via php and its a long code and i mean like it is possible but is there any way around with MySQL , through which we can make 2 columns unique if they both already exist just dont let user insert .
Use unique_index on your columns
ALTER TABLE `tablename` ADD UNIQUE `unique_index`(`columnOneName`, `columnTwoName`);
You can also use the following like sql while creating your table:-
CREATE TABLE `tableName` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`columnOne` int(11) DEFAULT NULL,
`columnTwo` int(11) DEFAULT NULL,
`columnThree` varchar(128),
PRIMARY KEY (`id`),
UNIQUE KEY `columnOne_columnTwo_unique_index` (`id_box_elements`,`id_router`)
);

PHP error , PRIMARY key [duplicate]

I don't understand why I'm getting this error when trying to populate this table. There is nothing in the table at the moment so I don't understand why there would be a duplicate...
This is the code I'm using:
INSERT INTO Suppliers
(supp_id,company_name,town,phone)
Values
("ADT217","AdTec","Birmingham","0121-368-1597"),
("CPS533","CPS","Maidenhead","01382-893715"),
("FCL162","ForComp Ltd","Nottingham","01489-133722"),
("KBC355","KBC Computers","Glasgow","0141-321-1497");
suppliers table...
CREATE TABLE suppliers(
supp_id int NOT NULL,
company_name character(15) NOT NULL,
town character(15)
phone character(15)
primary key(supp_id)
);
This occurs when you have a primary key but do not give it an initialization value. The insert itself is causing the duplication.
In your case, two possibilities come to mind:
supp_id is the primary key and declared as a number. In older versions of MySQL, I think the string values get silently converted to numbers. Because the leading characters are letters, the value is 0.
You have another id field that is the primary key, but given no value and not declared auto_increment.
EDIT:
I suspect you want the following code:
CREATE TABLE suppliers (
supplierId int NOT NULL auto_increment primary key,
supp_name varchar(255) unique,
company_name varchar(15) NOT NULL,
town varchar(15),
phone varchar(15)
);
INSERT INTO Suppliers(supp_name, company_name, town, phone)
Values ('ADT217', 'AdTec', 'Birmingham', '0121-368-1597'),
('CPS533', 'CPS', 'Maidenhead', '01382-893715'),
('FCL162', 'ForComp Ltd', 'Nottingham', '01489-133722'),
('KBC355', 'KBC Computers', 'Glasgow', '0141-321-1497');
Some notes:
Usually you want varchar() rather than char(), unless you really like lots of spaces at the end of strings.
I added a unique supplier name to the table and declared the id to be a auto_increment.
Single quotes are ANSI standard for string constants. MySQL (and some other databases) allow double quotes, but there is no reason to not use the standard.
With your table you can get the error like "Incorrect Integer Value", but depending on MySQL server configuration it can do conversion(string->int) automatically for your query string must become "0" as result of this it makes 2 rows with 0 as supp_id and get error Duplicate entry '0' for key 'PRIMARY'. I guess you are using InnoDB as table type, in this case query will run as transaction and it will rollback after first error(for this example it will be second row).
DROP TABLE suppliers; -- Will drop your old table
CREATE TABLE suppliers(
supp_id varchar(30) NULL, -- You can set length as you wish
company_name character(15) NOT NULL,
town character(15),
phone character(15),
primary key(supp_id)
);
INSERT INTO Suppliers
(supp_id,company_name,town,phone)
Values
("ADT217","AdTec","Birmingham","0121-368-1597"),
("CPS533","CPS","Maidenhead","01382-893715"),
("FCL162","ForComp Ltd","Nottingham","01489-133722"),
("KBC355","KBC Computers","Glasgow","0141-321-1497");
After changing type insert will work without problems.
In Wordpress, when we clone the website, the media and user roles are not working. The error is as below:
WordPress database error Duplicate entry '0' for key 'PRIMARY' for query
INSERT INTO `wp_334_actionscheduler_logs`
(`action_id`, `message`, `log_date_gmt`, `log_date_local`)
VALUES (0, 'action complete via WP Cron', '2021-02-17 05:29:40',
'2021-02-17 05:29:40')
made by
do_action_ref_array('action_scheduler_run_queue'),
WP_Hook->do_action,
WP_Hook->apply_filters,
ActionScheduler_QueueRunner->run,
ActionScheduler_QueueRunner->do_batch,
ActionScheduler_Abstract_QueueRunner->process_action,
do_action('action_scheduler_after_execute'),
WP_Hook->do_action,
WP_Hook->apply_filters,
ActionScheduler_Logger->log_completed_action,
ActionScheduler_DBLogger->log

avoiding duplicates in MySQL on mulitple column values

I keep finding myself writing queries to avoid inserting when there are duplicates - things like
select * from foobar where bar=barbar and foo=foofoo
and then checking in PHP with mysql_num_rows() to see if the number of results is > 0 to determine whether to go forward with my insert.
EDIT: for instance, let's say a user wants to send an invitation to another user. I want to make sure that in my invitations table, I don't add another entry with the same pair invited_id AND game_id. so this requires some sort of check.
this feels inefficient (and slightly dirty). is there a better way?
What about unique index?
A UNIQUE index creates a constraint such that all values in the index must be distinct. An error occurs if you try to add a new row with a key value that matches an existing row. For all engines, a UNIQUE index permits multiple NULL values for columns that can contain NULL.
http://dev.mysql.com/doc/refman/5.1/en/create-table.html
EDIT:
A column list of the form (col1,col2,...) creates a multiple-column index. Index values are formed by concatenating the values of the given columns.
http://dev.mysql.com/doc/refman/5.0/en/create-index.html
In this case, create a unique index on (bar, foo), so that the insert fails on duplicated value. You just need to handle the exception in php. This way, the code is cleaner and faster.
Just use a UNIQUE key on the columns and the INSERT IGNORE statement to insert new rows (duplicate rows are IGNORED).
Beware that the UNIQUE key may not exceed a 1000 bytes, meaning that the potential number of bytes contained in the fields foo and bar together may not exceed a 1000 bytes. If this creates a problem, just MD5 the CONCATENATED values into its own column at insert time, like (in PHP) md5($foo.$bar), and set the unique key to that column.
CREATE TABLE `test_unique` (
`id` int(10) unsigned NOT NULL auto_increment,
`foo` varchar(45) default NULL,
`bar` varchar(45) default NULL,
PRIMARY KEY (`id`),
UNIQUE INDEX `Unique` (`foo`,`bar`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
INSERT IGNORE INTO `test_unique` VALUES
(1, 'foo1', 'bar1'),
(2, 'foo2', 'bar2');
INSERT IGNORE INTO `test_unique` VALUES
(2, 'foo2', 'bar2');

Categories