I am trying to avoid inserting duplicates records into my table by using the PRIMARY KEY and INSERT IGNORE methods. As suggested # http://www.tutorialspoint.com/mysql/mysql-handling-duplicates.htm
I added the PRIMARY KEY to the tables definition as shown below:
mysql_connect("localhost", "root", "") or die(mysql_error());
mysql_select_db("flightSched") or die(mysql_error());
mysql_query("CREATE TABLE Alteration(
id INT NOT NULL AUTO_INCREMENT,
timePeriod TIME default '00:00:00',
depOrArriv VARCHAR(9),
flightNo VARCHAR(9) NOT NULL,
airline VARCHAR(20),
dest VARCHAR(30),
origin VARCHAR(30),
depature VARCHAR(8),
don VARCHAR(10),
arrivalTime VARCHAR(8),
arrivalTimeSec VARCHAR(28),
status VARCHAR(15) NOT NULL,
image_type varchar(25) not null default '',
image blob not null,
image_size varchar(25) not null default '',
image_name varchar(50) not null default '',
PRIMARY KEY (id, flightNo, status)
)")
or die(mysql_error());
echo "Table Created!";
Find below the INSERT IGNORE code:
mysql_query("INSERT IGNORE INTO Alteration
(depOrArriv, flightNo, airline, origin, don, arrivalTime, arrivalTimeSec, status, image_type, image, image_size, image_name)
VALUES('$depOrArriv', '$flightNo', '$airline', '$origin', '$don', '$arrivalTime', '$arrivalTime', '$status', '$image_type','$image', '$image_size', '$image_name' ) ");
// or die(mysql_error());
echo "Number of affected rows were: " . mysql_affected_rows();
While testing it I noticed that it STILL inserts duplicate records.
Why is it still doing this? Can anyone help me point out what is wrong?
Any help is greatly appreciated.
Looking forward to your feedback.
Your id column is auto incrementing which means each row is effectively unique when it is used in your key. You should inspect the data that you've inserted. You should see that each duplicate row actually has a separate and distinct id.
You can set a UNIQUE index on flightNo and status which would prevent the duplicate rows.
ALTER TABLE `Alteration` ADD UNIQUE (
`flightNo` ,
`status`
);
And then I would recommend just reducing your Primary Key to be id
UPDATE
As requested, this is a modified version of your code with a unique index used to prevent the duplicates:
mysql_connect("localhost", "root", "") or die(mysql_error());
mysql_select_db("flightSched") or die(mysql_error());
mysql_query("CREATE TABLE Alteration(
id INT NOT NULL AUTO_INCREMENT,
timePeriod TIME default '00:00:00',
depOrArriv VARCHAR(9),
flightNo VARCHAR(9) NOT NULL,
airline VARCHAR(20),
dest VARCHAR(30),
origin VARCHAR(30),
depature VARCHAR(8),
don VARCHAR(10),
arrivalTime VARCHAR(8),
arrivalTimeSec VARCHAR(28),
status VARCHAR(15) NOT NULL,
image_type varchar(25) not null default '',
image blob not null,
image_size varchar(25) not null default '',
image_name varchar(50) not null default '',
PRIMARY KEY (id),
UNIQUE KEY `flightNo` (`flightNo`,`status`)
)") or die(mysql_error());
echo "Table Created!";
mysql_query("INSERT IGNORE INTO Alteration (depOrArriv, flightNo, airline, origin, don, arrivalTime, arrivalTimeSec, status, image_type, image, image_size, image_name) VALUES('$depOrArriv', '$flightNo', '$airline', '$origin', '$don', '$arrivalTime', '$arrivalTime', '$status', '$image_type','$image', '$image_size', '$image_name' )");
echo "Number of affected rows were: " . mysql_affected_rows();
Related
I'm setting up a small signup form that should be inserting the data to an existing table, return the unique ID and insert that value to a secondary table.
Currently, I presume that the the first query is not running because the unique ID returned is 0.
I've gone over this small portion of code, that works on all my other developments and can't seem to figure out where it's blocking.
mysqli_query ($db_conx, "INSERT INTO Users
(first_name, last_name, dob, email, user_type, company, start_date, end_date, create_timestamp, last_modify_timestamp, create_matricule, pwd_hash)
VALUES
('$first_name','$last_name','$dob','$email','$user_type','$company','$start_date','$end_date','$create_timestamp','$create_timestamp','$create_matricule','$password_hash')");
//Now select this user to retreive the matricule
$matricule = mysqli_insert_id($db_conx);
$sql2 ="INSERT INTO Permissions (matricule) VALUES ('$matricule')";
$query2 = mysqli_query($db_conx, $sql2);
if(!$query){
echo json_encode(['message'=>"Error : ". mysqli_error($db_conx), 'code'=>500]);
}
echo json_encode(['message'=>"Matricule ".$matricule." created", 'code'=>200]);
}
The console returns the following :
Object { message: "Matricule 0 created", code: 200 }
javascript.js:125:13
success javascript.js:126:13
ReferenceError: matricule is not defined[Learn More]
So therefore the creation to the second table works just fine but not the first.
My database is configured as follows:
CREATE TABLE `Users` (
`matricule` int(6) NOT NULL,
`first_name` varchar(35) NOT NULL,
`last_name` varchar(35) NOT NULL,
`dob` date NOT NULL,
`email` varchar(50) NOT NULL,
`user_type` varchar(3) NOT NULL,
`company` varchar(30) NOT NULL,
`start_date` date NOT NULL,
`end_date` date NOT NULL,
`pwd_hash` varchar(500) NOT NULL,
`pwd_reset_hash` varchar(100) NOT NULL,
`otp_token` varchar(6) NOT NULL,
`create_timestamp` datetime NOT NULL,
`create_matricule` varchar(7) NOT NULL,
`manager_matricule` varchar(7) NOT NULL,
`sq_1` varchar(2) NOT NULL,
`sa_1` varchar(50) NOT NULL,
`sq_2` varchar(2) NOT NULL,
`sa_2` varchar(50) NOT NULL,
`last_modify_timestamp` datetime NOT NULL,
`last_modify_matricule` varchar(7) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
Thanks for any input!!
I think you mispelled some variable names.
You are fetching $query2 :
$query2 = mysqli_query($db_conx, $sql2);
then checks $query :
if(!$query){
echo json_encode(['message'=>"Error : ". mysqli_error($db_conx), 'code'=>500]);
}
There is most probably an issued in the structure of you database or the JavaScript you haven't shared.
First, you must make the quotation marks as follows.
$sql="INSERT INTO Users (first_name) VALUES ('".$first_name."')";
Or you can use prepared statements
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)
)";
I am working on a php site with uses mysql as database, now my site is a social network like site where users follow each other, now if a user joins in he is following nobody so his stream remains empty so they leave the site quickly as well,i want users to be following my account account automatically when he joins in. Can you please tell me how to do it
here are the two tables
Table structure for table sn_users
CREATE TABLE IF NOT EXISTS `sn_users` (
`id` int(11) NOT NULL,
`username` varchar(225) NOT NULL,
`email` varchar(225) NOT NULL,
`password` varchar(225) NOT NULL,
`name` varchar(225) DEFAULT NULL,
`picture` varchar(100) NOT NULL,
`cover` varchar(100) DEFAULT NULL,
`job` varchar(225) DEFAULT NULL,
`address` varchar(225) DEFAULT NULL,
`date` int(11) NOT NULL,
`reg_id` text,
`active` int(11) NOT NULL DEFAULT '1'
) ENGINE=MyISAM AUTO_INCREMENT=28 DEFAULT CHARSET=utf8;
Table structure for table sn_follows
CREATE TABLE IF NOT EXISTS `sn_follows` (
`id` int(11) NOT NULL,
`from` int(11) NOT NULL,
`to` int(11) NOT NULL,
`date` int(11) NOT NULL
) ENGINE=MyISAM AUTO_INCREMENT=74 DEFAULT CHARSET=utf8;
Run the query when the user get registerd.
<?
//Register query
$con = mysqli_connect("[HOST", "[USER]", "[PASS]", "[DB]");
$query1 = "INSERT INTO sn_users
(username, email, password, name, picture, cover, job, address, date, reg_id, active)
VALUES
('$username', '$email', '$password', '$name', '$picture', '$cover', '$job', '$address', 'date', 'reg_id', 'active')";
mysqli_query($con, $query);
//Auto follow query
$query2 = "INSERT INTO sn_follows
(`id`, `from`, `to`, `date`)
VALUES
([ID], '[NEW REGISTERD ACCOUNT], '[YOUR ACCOUNT]', '[DATE]')";
mysqli_query($con, $query2);
Hints:
Make of the field id in your database an auto_increment
Make sure you put a hashed password in the database
you need to do some modifications in your script.
1) get last inserted id of new registered user
2) insert that last id in sn_follows table with your id
this may elaborate flow
after your user register insert query get last id like below
example:
$sql = "INSERT INTO sn_users (firstname, lastname, email)
VALUES ('John', 'Doe', 'john#example.com')";
if (mysqli_query($conn, $sql)) {
$last_id = mysqli_insert_id($conn);
$sqlfloow = "insert into sn_follows (from,to,date) values("your id",$last_id,date("Y-m-d H:i:s"))";
}
I am trying to make a INSERT by UNIQUE and I am getting stuck, What I want too know is how I would do is make it so Column A is ALWAYS UNIQUE unless Column C has two different values and then it will insert into the database a second row for Column A where Column C is different.
a|b|c
-----
1|2|3
2|4|5
1|6|7
So I am currently using this sql table
CREATE TABLE `Player` (
`id` int(11) NOT NULL auto_increment,
`playername` varchar(255) NOT NULL,
`SteamID` varchar(255) NOT NULL UNIQUE,
`position` varchar(255) NOT NULL,
`lastlogin` varchar(255) NOT NULL,
`approved` varchar(255) NOT NULL,
`created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
) ENGINE=InnoDB;
With this query
$sql1= "INSERT IGNORE INTO Player (playername, SteamID, position, lastlogin, approved) VALUES ('$name', '$id', '$position', '$lastlogin', '$approve')";
It inserts the way I want so there is only 1 of each SteamID but it also will not insert if the same SteamID has two values for position.
EDIT:
What I have is a xml file I load up and insert data into the database based on the data in the xml file, What I need is below.
$xml = simplexml_load_file("players.xml");
foreach($xml->children() as $player)
{
$id = $player->attributes()->id;
$profile = new SteamProfile($id);
$name = mysql_real_escape_string($profile->getUsername());
$lastlogin = $player->attributes()->lastlogin;
$position = $player->lpblock->attributes()->pos;
$sql1= "INSERT IGNORE INTO Player (playername, SteamID, position, lastlogin, approved) VALUES ('$name', '$id', '$position', '$lastlogin', '$approve')";
if (!mysql_query($sql1,$connection))
{
die('Insert Error: ' . mysql_error());
}
}
so the xml file gets read and then the data in the file gets inserted into the database. sometimes the xml file would contain
<player id="76561197961716203" lastlogin="8/22/2014 10:49:28 PM">
<acl id="76561197961543041"/>
<acl id="76561197988417990"/>
<lpblock pos="273,93,-102"/>
<lpblock pos="1322,62,-1711"/>
</player>
at which point I would need a second row created for the second <lpblock pos=
So its currently inserting
|60|SwordFish |76561197961716203|273,93,-102|8/22/2014 10:49:28 PM|Yes|2014-08-24 15:28:16|
and it should be inserting
|60|SwordFish |76561197961716203|273,93,-102|8/22/2014 10:49:28 PM|Yes|2014-08-24 15:28:16|
|61|SwordFish |76561197961716203|1322,62,-1711|8/22/2014 10:49:28 PM|Yes|2014-08-24 15:28:16|
I'm not sure what you are trying to achieve, but you can set a UNIQUE restraint on a combination of columns, in your case SteamID and position:
CREATE TABLE `Player` (
`id` int(11) NOT NULL auto_increment,
`playername` varchar(255) NOT NULL,
`SteamID` varchar(255) NOT NULL,
`position` varchar(255) NOT NULL,
`lastlogin` varchar(255) NOT NULL,
`approved` varchar(255) NOT NULL,
`created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
UNIQUE KEY `unique_combination_of_two_fields` (`SteamID`,`position`)
) ENGINE=InnoDB;
Thanks for you help Jeroen I did this and its working.
foreach($player->children() as $lpblock)
{
$position = $lpblock->attributes()->pos;
if(!empty($position))
{
$sql1= "INSERT IGNORE INTO Player (playername, SteamID, position, lastlogin, approved) VALUES ('$name', '$id', '$position', '$lastlogin', '$approve')";
if (!mysql_query($sql1,$connection))
{
die('Insert Error: ' . mysql_error());
}
}
}
However I would like all of the SteamID's inserted and not just the ones with a $position set. When I take this out and try it adds the correct rows but also adds another row with a blank $position as if there is a SteamID that's blank when there is none.
if(!empty($position)){
}
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.