#1062 - Duplicate entry - php

I am working on a project of my own but I have an issue.
I created a simple table with the query:
$sql_art = "CREATE TABLE articoli (
id INT(3) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
cod_int VARCHAR(6) NOT NULL,
nome VARCHAR(50) NOT NULL,
descr VARCHAR(100) NULL,
cod_barre INT(20) NOT NULL,
prezzo INT(5) NULL,
note VARCHAR(100) NULL,
reg_date TIMESTAMP,
UNIQUE (cod_barre)
)";
when I try to add a new record with
$sql_ins = "INSERT INTO `gestionale_db`.`articoli`
(`id`, `cod_int`, `nome`, `descr`, `cod_barre`, `prezzo`, `note`, `reg_date`)
VALUES
(NULL, 'A001', 'Cazzilli', 'ancora caldi', '4545415615456',
'215', 'su tisi', CURRENT_TIMESTAMP)";
it return the error
#1062 - Duplicate entry '2147483647' for key 'cod_barre'
but obviously cod_barre is not equal to this value.
If I try to modify the record with UPDATE, it modify all the value except cod_barre that remain the same.
By default in php.ini I use InnoDB es ENGINE and latin1_swedish_ci as char_set.
Can anyone help me to find the error?

In your case you go to INT maximum 2147483647 = 2^{31}-1, because 4545415615456 is greater then 2147483647.
So you really insert row with max int value.
You need to create this table to fix your error:
$sql_art = "CREATE TABLE articoli (
id INT(3) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
cod_int VARCHAR(6) NOT NULL,
nome VARCHAR(50) NOT NULL,
descr VARCHAR(100) NULL,
cod_barre BIGINT(20) NOT NULL,
prezzo INT(5) NULL,
note VARCHAR(100) NULL,
reg_date TIMESTAMP,
UNIQUE (cod_barre)
)";

Related

mysql unique for multiple columns

When payment happen, sometimes its captured double entry in table.
I want to ignore double entry capture so i want to insert records when these created, user_id, amount fields should be unique.
How do i make it ? Below is my table.
CREATE TABLE `transactions` (
`id` int(20) NOT NULL AUTO_INCREMENT,
`created` datetime NOT NULL,
`modified` datetime NOT NULL,
`user_id` int(20) NOT NULL,
`project_id` int(20) DEFAULT NULL,
`foreign_id` int(20) NOT NULL,
`class` varchar(25) COLLATE utf8_unicode_ci NOT NULL,
`transaction_type_id` int(20) DEFAULT NULL,
`amount` float(10,2) NOT NULL,
`description` text COLLATE utf8_unicode_ci,
`payment_gateway_id` int(20) DEFAULT NULL,
`gateway_fees` float(10,2) NOT NULL,
`is_old` tinyint(1) NOT NULL DEFAULT '0',
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=266 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci
To strictly answer your question, you create a unique composite key on the combination of those 3 columns. That way no two rows can exist with a combination of the 3 of them in the composite index.
CREATE TABLE `transactions2` (
`id` int(20) NOT NULL AUTO_INCREMENT,
`created` datetime NOT NULL,
`modified` datetime NOT NULL,
`user_id` int(20) NOT NULL,
`project_id` int(20) DEFAULT NULL,
`foreign_id` int(20) NOT NULL,
`class` varchar(25) COLLATE utf8_unicode_ci NOT NULL,
`transaction_type_id` int(20) DEFAULT NULL,
`amount` float(10,2) NOT NULL,
`description` text COLLATE utf8_unicode_ci,
`payment_gateway_id` int(20) DEFAULT NULL,
`gateway_fees` float(10,2) NOT NULL,
`is_old` tinyint(1) NOT NULL DEFAULT '0',
PRIMARY KEY (`id`),
unique key(created,user_id,amount) -- <------------------- right here
);
insert some data to test it:
insert transactions2 (created,modified,user_id,project_id,foreign_id,class,
transaction_type_id,amount,description,payment_gateway_id,gateway_fees,is_old) values
('2009-01-01 12:00:00','2009-01-01 12:00:00',666,1,1,'a',1,100,'desc',1,12,1);
-- inserts fine (above)
Try it again with exactly the same data:
insert transactions2 (created,modified,user_id,project_id,foreign_id,class,
transaction_type_id,amount,description,payment_gateway_id,gateway_fees,is_old) values
('2009-01-01 12:00:00','2009-01-01 12:00:00',666,1,1,'a',1,100,'desc',1,12,1);
-- error 1062: Duplicate entry
-- change it barely:
insert transactions2 (created,modified,user_id,project_id,foreign_id,class,
transaction_type_id,amount,description,payment_gateway_id,gateway_fees,is_old) values
('2009-01-01 13:00:00','2009-01-01 12:00:00',666,1,1,'a',1,100,'desc',1,12,1);
-- inserts fine
Also, use ENGINE=INNODB. Read about that Here.
Please read Mysql multi column indexes a.k.a. composite indexes.
Lastly, the concept of what you are talking about is not far off from Insert on Duplicate Key Update. Just throwing that reference out there for you.
You can achieve the same using ,handling at the time of inserting,
You can try WHERE NOT EXISTS with INSERT.
Something like this.(You need to specify column name who has NOT NULL constraint,i missed all those columns)
INSERT INTO table_name(`created`,`user_id`,`amount`) VALUES =
'$created','$user_id','$amount'
WHERE NOT EXISTS
(SELECT *
FROM table_name
WHERE created ='$created' AND user_id='$user_id' AND amount='$amount')
Hope this helps.

inserting php + mysql

Its my first time using php and mysql together. Here's my database's script:
CREATE SCHEMA IF NOT EXISTS `Alinfo_Express` ;
USE `Alinfo_Express` ;
CREATE TABLE IF NOT EXISTS `Alinfo_Express`.`Categorias` (
`idCategoria` INT(11) NOT NULL,
`titulo` VARCHAR(128) NOT NULL,
`descricao` TEXT NOT NULL,
PRIMARY KEY (`idCategoria`))
ENGINE = InnoDB
DEFAULT CHARACTER SET = latin1;
CREATE TABLE IF NOT EXISTS `Alinfo_Express`.`Produtos` (
`idProduto` INT(11) NOT NULL,
`nome` VARCHAR(256) NOT NULL,
`descricao` TEXT NOT NULL,
`precoUnidade` FLOAT NOT NULL,
`qtdEstocada` INT(11) NOT NULL,
`emDestaque` BIT(1) NOT NULL,
`idCategoria` INT(11) NOT NULL,
PRIMARY KEY (`idProduto`),
INDEX `fk_Produtos_Categorias1_idx` (`idCategoria` ASC),
CONSTRAINT `fk_Produtos_Categorias1`
FOREIGN KEY (`idCategoria`)
REFERENCES `Alinfo_Express`.`Categorias` (`idCategoria`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB
DEFAULT CHARACTER SET = latin1;
CREATE TABLE IF NOT EXISTS `Alinfo_Express`.`Usuarios` (
`idUsuario` INT(11) NOT NULL,
`nome` VARCHAR(256) NOT NULL,
`sexo` CHAR(1) NOT NULL,
`cpf` VARCHAR(256) NOT NULL,
`rg` VARCHAR(256) NOT NULL,
`email` VARCHAR(256) NOT NULL,
`endereco` VARCHAR(256) NOT NULL,
`CEP` VARCHAR(256) NOT NULL,
`bairro` VARCHAR(256) NOT NULL,
`cidade` VARCHAR(256) NOT NULL,
`estado` VARCHAR(256) NOT NULL,
`senha` VARCHAR(256) NOT NULL,
`tipo` CHAR(1) NOT NULL,
PRIMARY KEY (`idUsuario`))
ENGINE = InnoDB
DEFAULT CHARACTER SET = latin1;
CREATE TABLE IF NOT EXISTS `Alinfo_Express`.`Compra` (
`idCompra` INT NOT NULL,
`valor` DECIMAL NOT NULL,
`tipoPagamento` VARCHAR(45) NOT NULL,
`dataCompra` DATETIME NOT NULL,
`idUsuario` INT(11) NOT NULL,
`idProduto` INT(11) NOT NULL,
PRIMARY KEY (`idCompra`),
INDEX `fk_Compra_Usuarios_idx` (`idUsuario` ASC),
INDEX `fk_Compra_Produtos1_idx` (`idProduto` ASC),
CONSTRAINT `fk_Compra_Usuarios`
FOREIGN KEY (`idUsuario`)
REFERENCES `Alinfo_Express`.`Usuarios` (`idUsuario`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_Compra_Produtos1`
FOREIGN KEY (`idProduto`)
REFERENCES `Alinfo_Express`.`Produtos` (`idProduto`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
Here's my code:
$MySQLi->query("INSERT INTO Produtos (idProduto, nome, descricao, precoUnidade,qtdEstocada, emDestaque, idCategoria) VALUES ($cod, '$nome', '$desc', $preco,$qtd, $dest, '$url', $cat);");
I don't know why it isn't working out. There's a long time I don't work with databases, that maybe be my problem.
You have couple of mistakes in your query. Try to execute in phpmyadmin. Try this one
$MySQLi->query("INSERT INTO Produtos (idProduto, nome, descricao, precoUnidade,qtdEstocada, emDestaque, idCategoria) VALUES ($cod, '$nome', '$desc', $preco, $qtd, $dest, '$url', $cat)");
It should work. In phpmyadmin, it will tell you error. Share it with us.
Here you can try with this i hope it will work
$MySQLi->query("INSERT INTO Produtos (idProduto, nome, descricao, precoUnidade,qtdEstocada, emDestaque, idCategoria) VALUES ('".$cod."', '".$nome."', '".$desc.'", '".$preco."','".$qtd."', '".$dest."', '".$url."', '".$cat."')");

Duplicate entry '2147483647' for key 'PRIMARY'

Based on what I've read here and on the web, you get this error if you try to store an integer > INT's maximum signed value; 2147483647. As you can see below, I used bigint(20) for user_id. So, I don't know why I'm getting this error.
CREATE TABLE IF NOT EXISTS `users` (
`user_id` bigint(20) unsigned NOT NULL,
`screen_name` varchar(20) NOT NULL,
`name` varchar(20) DEFAULT NULL,
`profile_image_url` varchar(200) DEFAULT NULL,
`created_at` datetime NOT NULL,
`followers_count` int(10) unsigned DEFAULT NULL,
`friends_count` int(10) unsigned DEFAULT NULL,
`statuses_count` int(10) unsigned DEFAULT NULL,
`last_update` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`user_id`),
KEY `user_name` (`name`),
KEY `last_update` (`last_update`),
KEY `screen_name` (`screen_name`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
The php script that handles the insertion:
/* Prepare an insert statement */
$query = "INSERT INTO users (user_id, screen_name, name, profile_image_url, created_at, followers_count, friends_count, statuses_count) VALUES (?,?,?,?,?,?,?,?)";
$stmt = $mysqli->prepare($query);
$stmt->bind_param("issssiii", $user_id, $screen_name, $name, $profile_image_url, $created_at, $followers_count, $friends_count, $statuses_count);
/* Execute the statement */
$stmt->execute()
FYI: the purpose of this script & table is to store some of Twitter's users data
INT has a maximum signed value of 2147483647. Any number greater than that will be truncated to that value. What you need to do is change that column to be a user_id varchar(20) unsigned NOT NULL, which will hold strings of up to 20 characters since cards numbers are strings and not actually numbers (you don't do math with the). You also should remove AUTO_INCREMENT as that is not a value you will be incrementing.

Why mysql_insert_id returns 0 in my case?

This is my table:
CREATE TABLE `users` (
`id` int(10) unsigned NOT NULL auto_increment,
`name` varchar(20) NOT NULL default '',
`pass` varchar(32) NOT NULL default '',
`lang` varchar(2) default NULL,
`locale` varchar(2) default NULL,
`pic` varchar(255) default NULL,
`sex` char(1) default NULL,
`birthday` date default NULL,
`mail` varchar(64) default NULL,
`created` timestamp NOT NULL default CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
UNIQUE KEY `mail` (`mail`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=27 ;
And this is my query:
$query = "INSERT IGNORE INTO `users` (`name`, `mail`, `birthday`, `lang`, `locale`, `sex`, `pic`) VALUES ('".$name."', '".$email."', '".date_format($birthdaynew, 'Y-m-d H:i:s')."', '".substr($locale, 0, 2)."', '".substr($locale, -2, 2)."', '".$sex."', 'pic/".$uid.".jpg')";
$rows = mysql_query($query) or die("Failed: " . mysql_error());
$_SESSION['id'] = mysql_insert_id(); // I have tryed also mysql_insert_id($db_con) where $db_con is the link to db.
$_SESSION['name'] = $name;
$_SESSION['name'] contains correctly the name but $_SESSION['id'] contains 0.
Why ?
I'm going crazy!
Is there a particular reason why you are using INSERT IGNORE?
If you use INSERT IGNORE, then the row won't actually get inserted if there is a duplicate key (PRIMARY or UNIQUE), or inserting a NULL into a column with a NOT NULL constraint.
Referring to the pass column, as you have not defined anything to insert into it, and it has NOT NULL constraint.
EDIT:
Referring also to the mail column, as you have a UNIQUE constraint on it.

Auto_increment stops script from creating table

My server is on hostgator running on a linux centOS.
I'm simply trying to create a table within my database and I figured out how to get the table to get created. Although when I add the AUTO_INCREMENT setting the code doesn't execute and the table isn't created.
Why would this be and how can I correct it?
Here is my code:
$members2_table = "CREATE TABLE ninja08_codin.members2(
id INT NOT NULL AUTO_INCREMENT,
first_name VARCHAR(40),
last_name VARCHAR(40) NOT NULL,
email VARCHAR(64) NOT NULL,
date_joined TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
cred VARCHAR(10) NOT NULL)";
To use AUTO_INCREMENT you may have to assign the column as a primary key:
$members2_table = "CREATE TABLE ninja08_codin.members2(
id INT NOT NULL AUTO_INCREMENT,
first_name VARCHAR(40),
last_name VARCHAR(40) NOT NULL,
email VARCHAR(64) NOT NULL,
date_joined TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
cred VARCHAR(10) NOT NULL,
PRIMARY KEY (id))";
Your query will give error
there can be only one auto column and it must be defines as a key, so add primary key to id field
$members2_table = "CREATE TABLE ninja08_codin.members2(
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
first_name VARCHAR(40),
last_name VARCHAR(40) NOT NULL,
email VARCHAR(64) NOT NULL,
date_joined TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
cred VARCHAR(10) NOT NULL)";

Categories