Auto_Increment not working on insert query - mysql

Need help how to solve this problem...
I have created a users table which has following columns
Create table users
(
uid int(10) PRIMARY KEY AUTO_INCREMENT,
uname varchar(50),
password varchar(50),
email varchar(50)
);
when i insert values with uid it executes successfully :
Insert into users values(1,'ABC','Helloworld','ABC#gmail.com');
but when i try without uid
Insert into users values('SDC','Helloworld','SDC#gmail.com');
it does not execute successfully and gives an error
ERROR 1136 (21S01): Column count doesn't match value count at row 1
my uid has AUTO_INCREMENT so it should automatically increase..

Of course auto_increment is working correctly. You just need to learn best practices about using insert. Always list all the columns (unless you really, really know what you are doing):
Insert into users (uname, password, email)
values('SDC', 'Helloworld', 'SDC#gmail.com');
The id column will be auto-incremented. If you don't list the columns, then MySQL expects values for all columns, including the auto-incremented one.

Related

Use last inserted id as username

i would like that whenever i insert a row the newly generated id be used as a username and also get inserted in the user_name field. Any idea on how how i can achieve this will be much appretiated.
I have tried to run the below code on mysql workbench,and everything seem to work fine except for the insert statement.
create database if not exists mydatabase;
create table if not exists mydatabase.mytable
(
id int auto_increment not null,
user_name int not null,
pass_word varchar(100),
primary key(id)
);
insert into mydatabase.mytable(user_name,pass_word) values (select SCOPE_IDENTITY(),'mypass');
Not sure if your version of sql supports multiple auto_increment columns. However I'm thinking you could either create a trigger or insert the following every time you do an insert:
update my_table
set user_name = id

SQL changing the id when running a join statement in VS Studio

I recently started to work with SQL in the Visual Studio environment, I have created the following two tables and populated them with values, these are the command for the creation of the tables users and photos:
CREATE TABLE users(
id INTEGER AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(255) UNIQUE NOT NULL,
created_at TIMESTAMP DEFAULT NOW()
);
CREATE TABLE photos(
id INTEGER AUTO_INCREMENT PRIMARY KEY,
image_url VARCHAR(255) NOT NULL,
user_id INTEGER NOT NULL,
created_at TIMESTAMP DEFAULT NOW(),
FOREIGN KEY(user_id) REFERENCES users(id)
);
Now these are the statements that I ran to populate the tables
INSERT INTO users(username) Values
('Colton'),('Ruben');
INSERT INTO photos(image_url,user_id) VALUES
('/alskjd76',1),
('/lkajsd98',2);
Now if I run the statement
SELECT *
FROM photos
JOIN users;
I get the tables:
Now if I run the command:
SELECT *
FROM users
JOIN photos;
I get the table
Here are the tables of users and the tables for photos.
Now my question is why is it that "id" column in the second table is changed to 4,4,5,5 when the actual "id" column of the users table only contains the values 1,2? The first instance seems to respect this why doesn't the second?
EDIT: It seems to be displaying the following now when running the commands
SELECT *
FROM photos
JOIN users;
and when I run :
SELECT *
FROM users
JOIN photos;
Edit: this seems to be correct now, is this right, it seems to have been solved with the deletion and recreation of the tables entirely. I think that V.S studio might have mistakenly taken the table to have more present photos with id's 1-3.

Duplicate entry '0' for key 'PRIMARY'

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

WEBSQL simple insert into populated table

Can't seem to figure out why this simple statement doesn't work
tx.executeSql("INSERT INTO history SELECT * FROM scan");
It works correctly if the table history is empty which is not of much use but if the table history has any data then it does not carry out the insert I must do:
tx.executeSql("DELETE FROM history", []);
tx.executeSql("INSERT INTO history SELECT * FROM scan");
Any ideas? Cheers
Edit:
Structures are the same:
tx.executeSql("CREATE TABLE IF NOT EXISTS scan(ID INTEGER NOT NULL PRIMARY KEY, sunum TEXT, binnum TEXT, userid TEXT, added_on DATETIME, upload_on DATETIME)");
tx.executeSql("CREATE TABLE IF NOT EXISTS history(ID INTEGER NOT NULL PRIMARY KEY, sunum TEXT, binnum TEXT, userid TEXT, added_on DATETIME, upload_on DATETIME)");
The problem is that you're attempting to insert a duplicate primary key value into the History table. From your structure, they both have ID listed as a PRIMARY KEY, which cannot contain duplicate values.
Try specifying all columns except for that key:
INSERT INTO History
(sunum, binnum, userid, added_on, upload_on)
SELECT sunum, binnum, userid, added_on, upload_on
FROM Scan
Though, looking at the structure, the ID values aren't auto-incremented. If you don't care what the ID is, you can declare the ID column as: ID INT NOT NULL AUTO_INCREMENT.
If you need to pull the ID over from the other table, you'll have to do an upsert or merge into that table.

how to pass a null value to a foreign key field?

I have 2 tables:
university:
university_id(p.k) | university_name
and user:
uid | name | university_id(f.k)
How to keep university_id NULL in user table?
I am writting only 1 query, my query is:
INSERT INTO user (name, university_id) VALUES ($name, $university_id);
Here $university_id can be null from front end.
university table will be set bydefault by me.
In the front end, student will select the university name, according to that the university_id will pass to user table, but if student is not selecting any university name then is should pass null value to the user table for university_id field.
Just allow column university_id of table user to allow NULL value so you can save nulls.
CREATE TABLE user
(
uid INT NOT NULL,
Name VARCHAR(30) NOT NULL,
university_ID INT NULL, -- <<== this will allow field to accept NULL
CONSTRAINT user_fk FOREIGN KEY (university_ID)
REFERENCES university(university_ID)
)
UPDATE 1
based on your comment, you should be inserting NULL and not ''.
insert into user (name,university_id) values ('harjeet', NULL)
UPDATE 2
$university_id = !empty($university_id) ? "'$university_id'" : "NULL";
insert into user (name,university_id) values ('harjeet', $university_id);
As a sidenote, the query is vulnerable with SQL Injection if the value(s) of the variables came from the outside. Please take a look at the article below to learn how to prevent from it. By using PreparedStatements you can get rid of using single quotes around values.
How to prevent SQL injection in PHP?
Here suppose i have foreign key user_id and i want to insert null value for that.
Checkbox must be checked for insert null value for foreign key.
I was using MySQL InnoDB and even allowing NULL in the FK column and using NULL as default I was getting an error.
So I used the SET syntax:
INSERT INTO (table) SET value1=X...
And I just don't set the FK column.