PHP error , PRIMARY key [duplicate] - php

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

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 MySql 2 column as index and 1 as another index?

I'm using php and i have a table that have 2 column of varchar , one is used for user identification, and the other is used for page name entry.
they both must be varchar.
i want to insert ignore data when user enter a page to know if he visited it or not, and i want to fetch all the rows that the user have been in.
fetch all for first varchar column.
insert if not exist for both values.
I'm hoping to do it in the most efficient way.
what is the best way to insert without checking with another query if exist?
what is the best way other then:
SELECT * FROM table WHERE id = id
to fetch when the column needed is varchar?
You should consider a normalized table structure like this:
CREATE TABLE user (
id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100)
);
CREATE TABLE page (
id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100)
);
CREATE TABLE pages_visted (
id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
user_id INT UNSIGNED,
page_id INT UNSIGNED,
UNIQUE KEY (user_id, page_id)
);
INSERT IGNORE INTO pages_visted (user_id, page_id) VALUES (:userId, :pageId);
SELECT page_id FROM pages_visted WHERE user_id = :userId;
I think you want to implement a composite primary key.
A composite primary key tells MySQL that you want your primary key to be a combination of fields.
More info here: Why use multiple columns as primary keys (composite primary key)
I don't know of a better option for your query, although I can advise, if possible:
Define columns to be NOT NULL. This gives you faster processing and requires less storage. It will also simplify queries sometimes because you don't need to check for NULL as a special case.
And with variable-length rows, you get more fragmentation in tables where you perform many deletes or updates due to the differing sizes of the records. You'll need to run OPTIMIZE TABLE periodically to maintain performance.

How to ensure unique number sequentially in php using mysql?

I am developing an web application where I have to give every new registrant a serial number. The main issue is with 'how to ensure uniqueness?'. I have searched through the different functions available with mysql and found mysql_insert_id() to be the fittest solution here. But before I run towards it, I need to know whether this function is thread-free. To more precise, say there are two users sitting at two different terminals and submits the registration form synchronously. Will they both get the same id out of the execution of the function mysql_insert_id()? Otherwise, my project will spoil. Please help. If I could not clear my point, please comment. Thanks in advance.
here is detailed solution
CREATE TABLE Persons
(
ID int NOT NULL AUTO_INCREMENT,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255),
PRIMARY KEY (ID)
)
By default, the starting value for AUTO_INCREMENT is 1, and it will increment by 1 for each new record.
To insert a new record into the "Persons" table, we will NOT have to specify a value for the "ID" column (a unique value will be added automatically):
If you have an id column on your table in your database and that column is set to be the primary key that will be enough. Even if 2 people will submit the form at the same the ids will be unique.
id column could be defined like this
ADD PRIMARY KEY (`id`)
id` int(11) NOT NULL AUTO_INCREMENT
Alternatively, you can use the UUID() function in mysql.
A UUID is designed as a number that is globally unique in space and
time. Two calls to UUID() are expected to generate two different
values, even if these calls are performed on two separate computers
that are not connected to each other.
mysql> SELECT UUID();
-> '6ccd780c-baba-1026-9564-0040f4311e29'
For further details : http://dev.mysql.com/doc/refman/5.0/en/miscellaneous-functions.html#function_uuid

Error in SQL syntax DATATIME option

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

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