if duplicate entry get id - php

My problem in mysql.
My Table name is categories.
CREATE TABLE IF NOT EXISTS `categories` (
`cid` int(10) NOT NULL AUTO_INCREMENT,
`category_name` char(100) DEFAULT NULL,
`parent` int(10) DEFAULT NULL,
PRIMARY KEY (`cid`),
UNIQUE KEY `parent` (`parent`,`category_name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
parent and category_name are unique fields.
If the record not exists I would like to run insert into command.;
select last_insert_id() #get last insert id.
UPDATE
MY PHP Code is:
$sql = "insert into categories (parent,category_name) values ('".$field[parent]."','".$temp->cat_name."')";
if (#$db->query($sql)){
$cid = $db->get_var("select last_insert_id()");
}else{
$cid = $db->get_var("SELECT cid FROM categories WHERE parent=".$field[parent]." and category_name='".$temp->cat_name."'");
}
How can I get exist id return?

If the record not exists I would like to run insert into command.;
You can use INSERT IGNORE ....
INSERT IGNORE INTO `categories` ( `category_name`, `parent` ) values ('A', 1); // will insert it
INSERT IGNORE INTO `categories` ( `category_name`, `parent` ) values ('A', 1); // will ignore it
INSERT IGNORE INTO `categories` ( `category_name`, `parent` ) values ('A', 2); // will insert it
INSERT IGNORE INTO `categories` ( `category_name`, `parent` ) values ('B', 2); // will insert it
INSERT IGNORE INTO `categories` ( `category_name`, `parent` ) values ('B', 2); // will ignore it
From the docs:
If you use the IGNORE keyword, errors that occur while executing the INSERT statement are treated as warnings instead. For example, without IGNORE, a row that duplicates an existing UNIQUE index or PRIMARY KEY value in the table causes a duplicate-key error and the statement is aborted. With IGNORE, the row still is not inserted, but no error is issued.

select last_insert_id()
return a ID after the successful insert. for further processing you can store it in your database after a successful insert.
also you can use insert ignore into .... for avoid duplicate insert

I think this is the best way to do it:
$sql = "insert into categories (parent, category_name) values ('".$field[parent]."','".$temp->cat_name."') ON DUPLICATE KEY UPDATE cid=LAST_INSERT_ID(cid)";
$db->query($sql);
$cid = $db->insert_id;
var_dump($cid);

Related

Query consult doctrine composite key

Hello I am try to take data with dictrine 2.5 from a table but I do not know how to do it.
SQL FILE
DROP DATABASE composite_key;
CREATE DATABASE composite_key;
USE composite_key;
CREATE TABLE company (
id_company INT NOT NULL AUTO_INCREMENT,
name VARCHAR(200) NULL,
PRIMARY KEY (id_company)
);
CREATE TABLE users (
id_user INT NOT NULL AUTO_INCREMENT,
name VARCHAR(200) null,
PRIMARY KEY (id_user)
);
CREATE TABLE reference (
id_company INT NOT NULL,
id_user INT NOT NULL,
createat TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (id_company),
FOREIGN KEY (id_company) REFERENCES company(id_company),
FOREIGN KEY (id_user) REFERENCES users(id_user)
);
INSERT INTO users (`name`) VALUES ('test1');
INSERT INTO users (`name`) VALUES ('test2');
INSERT INTO users (`name`) VALUES ('test3');
INSERT INTO company (`name`) VALUES ('company1');
INSERT INTO company (`name`) VALUES ('company2');
INSERT INTO company (`name`) VALUES ('company3');
INSERT INTO reference (`id_company`,`id_user`) VALUES (1,1);
INSERT INTO reference (`id_company`,`id_user`) VALUES (2,2);
INSERT INTO reference (`id_company`,`id_user`) VALUES (3,3);
QUERY WHICH I HAVE TRIED
$dql = "SELECT r FROM CompositeBundle:Reference r JOIN CompositeBundle:Company c JOIN CompositeBundle:Users u WHERE c.idCompany = 1 AND u.idUser = 1 ";
$dql = "SELECT r FROM CompositeBundle:Reference r JOIN r.idUser JOIN r.idCompany WHERE r.idCompany = 1 AND r.idUser = 1 ";
If somone know to do these dql please sat It.

INSERT if not exists UPDATE if exists does not work

I am trying to have the solution of the very well known INSERT IF NOT EXISTS UPDATE IF EXISTS.
But mine is not working. I don't know why, Can anyone figure it out?
Here is what I have tried yet:
$qprep = ("INSERT INTO gpsdata (`imei`,`latitude`,`longitude`)
VALUES ('$imei','$lathex1','$lonhex1') ON DUPLICATE KEY UPDATE
latitude='$lathex1',longitude='$lonhex1';");
I want to update the row if the same "imei" is in there, or Insert if its not.
I have my ROW as the primary key and from phpmyadmin, I have made the imei "unique".
What am I doing wrong?
My SQL DUMP:
CREATE TABLE IF NOT EXISTS `gpsdata` (
`ROW` int(11) NOT NULL AUTO_INCREMENT,
`IMEI` varchar(255) NOT NULL,
`Latitude` varchar(255) NOT NULL,
`Longitude` varchar(255) NOT NULL,
PRIMARY KEY (`ROW`),
UNIQUE KEY `IMEI` (`IMEI`,`Latitude`,`Longitude`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=36 ;
--
-- Dumping data for table `gpsdata`
--
INSERT INTO `gpsdata` (`ROW`, `IMEI`, `Latitude`, `Longitude`) VALUES
(24, '#2:359672050035420:2:*', '90.370803333333', '0'),
(30, '#2:359672050035420:2:*', '90.370803333333', '23.7584'),
(27, '#2:359672050035420:2:*', '90.370803333333', '23.75854'),
(35, '1:135790246811221:1:*', '1.0961283333333', '1.759595'),
(32, '1:135790246811221:1:*', '1.759595', '1.0961283333333');
As seen here, you need to replace the actual values in the update statement with either A| references to the alreay existing values (e.g. longitude=longitude) or B| references to the new values (e.g. longitude=VALUES(longitude), but not longitude='$lonhex1').
Your query should be rewritten:
$qprep = ("INSERT INTO gpsdata (`imei`,`latitude`,`longitude`)
VALUES ('$imei','$lathex1','$lonhex1') ON DUPLICATE KEY UPDATE
latitude=VALUES(latitude),longitude=VALUES(longitude)");
If you have statement based replication running on this server then there would be a problem, see the warning below:
Unsafe statement written TO the BINARY LOG USING statement FORMAT
since BINLOG_FORMAT = STATEMENT. INSERT... ON DUPLICATE KEY UPDATE
ON a TABLE WITH more THAN ONE UNIQUE KEY IS unsafe
You have to pass the column name and its value on which you have used the primary key or unique key on which you want the Duplicate Key Update.
If it gets the id(in your case ROW, latitude and longitude column on which primary and unique key is defined ) in the database, it updates it, else it inserts a new row.
$qprep = ("INSERT INTO gpsdata (`imei`,`latitude`,`longitude`)
VALUES ('$imei','$lathex1','$lonhex1') ON DUPLICATE KEY UPDATE
latitude=VALUES(latitude),longitude=VALUES(longitude)");
Example:
INSERT INTO gpsdata (`row`,`imei`,`latitude`,`longitude`)
VALUES ('24','1','TEST','TEST') ON DUPLICATE KEY UPDATE
`IMEI`='2', `Latitude`='2',`Longitude`='2';
or
INSERT INTO gpsdata (`imei`,`latitude`,`longitude`)
VALUES ('1','TEST','TEST') ON DUPLICATE KEY UPDATE
`IMEI`='2', `Latitude`=VALUES(`Latitude`),`Longitude`=VALUES(`Longitude);

SQL insert into table if row not exists in empty table not working

I've a problem,
I want insert fields in a table if row not exist
My code is:
INSERT INTO `myTable` (
`circuit` ,
`date` ,
`session` ,
`lap` ,
`time`
) SELECT 'misano', '2013-10-11', 1, 1, '0:01:06:332'
FROM `myTable`
WHERE NOT EXISTS (SELECT 1 FROM `myTable` WHERE `circuit` = 'misano' AND `date` = '2013-10-11' AND `session` = 1 AND `lap` = 1 AND `time` = '0:01:06:332')
This code work fine if in "myTable" there is at least one row. If "myTable" is empty, SQL return: 0 row.
If myTable is empty, then a SELECT ... FROM myTable will never produce any rows (even without the WHERE condition).
Use
FROM dual
in the outer select. The DUAL pseudo table always contains exactly one row. The EXISTS sub-query runs against myTable of course.
Edit:
If you have a unique index on myTable, see the solution suggested by Filipe.
If you have a primary key or unique index in your table, you could use INSERT ... ON DUPLICATE KEY UPDATE
INSERT INTO `myTable` (`circuit`, `date`, `session`, `lap`, `time`)
VALUES ('misano', '2013-10-11', 1, 1, '0:01:06:332')
ON DUPLICATE KEY
UPDATE `circuit` = VALUES (`circuit`),
`date` = VALUES (`date`),
`session` = VALUES (`session`),
`lap` = VALUES (`lap`),
`time` = VALUES (`time`)

Fastest way to update a MySQL table if row exists else insert. More than 2 non-unique keys

I have the following table structure:
CREATE TABLE IF NOT EXISTS `reports` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`day` int(11) NOT NULL,
`uid` int(11) NOT NULL,
`siteid` int(11) NOT NULL,
`cid` int(3) NOT NULL,
`visits` int(11) NOT NULL,
PRIMARY KEY (`id`)
)
Currently i check & insert/update with the following snippet:
$checkq = mysql_query("SELECT count(*) as rowexist FROM reports WHERE day='$day' AND uid='$uid' AND siteid='$sid' AND cid='$cid'") or die(mysql_error());
$checkr = mysql_fetch_array($checkq);
if ($checkr['rowexist'] > 0) {
mysql_query("UPDATE reports_adv SET visits=visits+1 WHERE day='$day' AND uid='$uid' AND siteid='$sid' AND cid='$cid'");
} else {
mysql_query("INSERT INTO reports_adv SET day='$day', uid='$uid', siteid='$sid', cid='$cid', visits='1'");
}
Is a fastest way to update this MySQL table if row exists else insert with more than 2 non-unique keys?
just use INSERT...ON DUPLICATE KEY UPDATE
INSERT INTO reports_adv (day, uid, siteid, cid, visits)
VALUES ('$day', '$uid', '$sid', '$cid', 1)
ON DUPLICATE KEY UPDATE visits=visits+1;
INSERT ... ON DUPLICATE KEY UPDATE Syntax
but before anything else, you should define a UNIQUE constraint on the columns.
ALTER TABLE reports_adv ADD CONSTRAINT tb_uq UNIQUE (day, uid, siteid, cid)

PHP: use id to another column

Ok, so i have a normal query that inserts to the database.
mysql_query("INSERT INTO users_pm_in (uID, msg) VALUES ('$uID', '$msg')");
Now this table has also a column called "id" with auto_increment & primary key.
When it inserts it auto makes number for the column in the row. Now I want this number, and put it in column dialog, in the same row. So the inserted row have the same number/id in "id" and "dialog". How can i do that?
Not sure if this can be done in one query (or why you even want to do this), but you can use this:
mysql_query("INSERT INTO users_pm_in (uID, msg) VALUES ('$uID', '$msg')");
mysql_query("UPDATE users_pm_in SET dialog = id WHERE id = '".mysql_insert_id()."');
Be sure to escape the variables properly also.
I think it would be easier to remove the autoincrement and add the id+dialog value yourself.
Check out mysql_insert_id()
You can do this, altough it's not very efficient...
Supose you have this table:
CREATE TABLE `test` (
`id` INT(10) NOT NULL AUTO_INCREMENT,
`a` INT(10) NULL DEFAULT '0',
`b` INT(10) NULL DEFAULT '0',
PRIMARY KEY (`id`)
)
ENGINE=MyISAM
ROW_FORMAT=DEFAULT
You can perform the following query:
INSERT INTO test (a, b) SElECT IFNULL((MAX(id) +1),1), 200 FROM test;
Notice that "200" is some random value that will be inserted on "b" column.

Categories