MYSQL update if exists or insert - php

I have been trying to get the following SQL to work however it seems to skip the insert function. Essentially updating should take priority as most of the time it should fire.
UPDATE `teams-tasks`
SET status=(:s), name=(:n), description=(:d), importance=(:i), applies=(:a)
WHERE teamId =(:t) AND date=(:da) AND playerId =(:p) AND creatorId =(:c);
IF (SELECT ROW_COUNT() = 0);
INSERT INTO `teams-tasks`
( status, date, creatorId, teamId, playerId, name, description, importance, applies )
VALUES
( (:s), (:da), (:c), (:t), (:p), (:n), (:d), (:i), (:a) ))
what am i doing wrong?
i am using php pdo for my database connection if it matters
thanks

User replace into query which makes sure if the row exists it will update the data, if row does not exists it will insert the date.
to check the duplicate entry it compares the primary key internally
e.g.
REPLACE INTO table_name(column_name1,column_name2,…)
VALUES(value1,value2,…)
e.g.
REPLACE INTO offices(officecode,city)
VALUES(8,'San Jose')
Thanks
Amit

You should use INSERT ... ON DUPLICATE KEY UPDATE
For example
INSERT INTO AggregatedData (datenum,Timestamp)
VALUES ("734152.979166667","2010-01-14 23:30:00.000")
ON DUPLICATE KEY UPDATE
Timestamp=VALUES(Timestamp)

Related

ON DUPLICATE KEY UPDATE - Condition WHERE vs CASE WHEN vs IF?

I am refering to this post. I am stuck with a problem I can't resolve. I try to insert multiple rows with a php script into a MySQL database. I don't succeed in updating the whole thing using ON DUPLICATE KEY UPDATE and using a WHERE condition (at the end of the code below) I would like to use to update only an entry has been modified recently:
// for information (used in a foreach loop):
$args[] = '("'.$row['lastname'].'", '.$row['phone'].', "'.$row['lastModification'].'")';
// then:
$stringImplode = implode(',', $args);
// Where I am stuck - WHERE statement:
$sql = $mysqli->query('INSERT INTO table_name '. (lastname, phone, timestamp) .' VALUES '.$stringImplode .'ON DUPLICATE KEY UPDATE lastname=VALUES(lastname), phone=VALUES(phone) WHERE timestamp > VALUES(lastModification);
Everything works fine except I cannot set any WHERE condition at this point that involves multiples entries. Maybe the WHERE statement in this case is not intended to refer to a condition in this statement.
I was told to try with a database procedure using a JOIN statement and a temporary table with first all my entries and then querying some conditions. But I have to admit I don't understand very well how I could leverage such a table to update an other table.
Is there an easy and lovely way to use a "CASE WHEN" or an "IF" statement in this case?
Would something like
INSERT INTO ... ON KEY DUPLICATE UPDATE lastname = VALUES(lastname), phone = VALUES(phone)
CASE WHEN (timestamp > VALUES(lastModification)) THEN do nothing ...
or
...ON KEY DUPLICATE UPDATE... IF (timestamp > VALUES(lastModification)) ...
If anyone could help me, I would be very grateful.
EDIT: Since I will have many variables, could it be used in this way:
INSERT INTO ... ON KEY DUPLICATE UPDATE
IF(timestamp > VALUES(timestamp),
(
name = VALUES(name),
number = VALUES(number),
timestamp = VALUES(timestamp)
....many other variables
),
(
name = name,
number = number,
timestamp = timestamp
....many other variables)
)
You can use simple IF function in value like this:
INSERT INTO ... ON KEY DUPLICATE UPDATE
name = VALUES(name),
number = VALUES(number),
timestamp = IF(timestamp > VALUES(timestamp), VALUES(timestamp), timestamp)
If condition is not met, it will update timestamp with the same timestamp which already exists. It does not matter, because update to same values is optimized before it is even executed, so MySQL will not make real update. You should not afraid of some performance penalty.
EDIT:
IF works likes this:
IF(condition, returned when true, returned when false)
Maybe you need to switch those two arguments to fit your condition like you want.

PHP MySQLi insert get last column value add 1

I'm trying to run an INSERT query into a table with 3 columns. The first column is where I'm having the issue.
It is called COMM_CODE with VARCHAR value of 10 length, and is the primary key, ALLOW NULL is unchecked.
The values for COMM_CODE look like this:
COMM_CODE
c20188
c20189
c20190
// and so on
What I would like to do, is when a new record is inserted, to basically add 1 to the most recent record.
Therefore, the most recent record is:
c20190
So when I add a new record, the COMM_CODE for the new record will be:
c20191
I tried this:
INSERT INTO table_c
(COMM_CODE, COMM_DESC, DATE)
VALUES
(''+1, 'VIDEO GAMES', NOW());
But that just adds a number 1 to that column.
How can I make this happen?
Here the solution for your query :
To generate the new code I'hv created get_new_code function in mysql. I hope you know how funcions work in mysql.
CREATE FUNCTION `get_new_code`() RETURNS varchar(11)
BEGIN
Declare var_code VARCHAR(11);
SELECT max(`COMM_CODE`) INTO var_code FROM table_c;
RETURN (CONCAT('c',(convert(substr(var_code,2,length(var_code)), SIGNED INTEGER)+1)));
END
Just to verify your logic you can use :
select get_new_code();
So that you will get the clear picture.
Call this get_new_code function in insert query like this :
INSERT INTO
`table_c`(`COMM_CODE`, `COMM_DESC`, `COMM_DATE`)
VALUES
(get_new_code(),'Description text',NOW());
This should solve your problem. :)

INSERT only if both colomns are not duplicate

DELETE FROM RelationsAuthors WHERE MainId = :MainId AND AuthorId NOT IN (:authorarray)
The above code will delete anything that is not in authorarry and where MainId equals a specific value.
After the deletion I would like to insert the values of authoarray into the database if they do not exist without getting any errors.
*with using foreach $_POST['AuthorId']:
INSERT INTO RelationsAuthors (Id,MainId,AuthorId) VALUES('',:MainId,:AuthorId)
However I would like to add to my code that I need to INSERT only WHERE (MainId = :MainId AND AuthorId = :AuthorID) does not exist. How can I do that?
First, create a unique index on the two fields so the database will prevent duplicates for you:
create unique index idx_RelationsAuthors_MainId_AuthorId on RelationsAuthors(MainId, AuthorId);
Then the insert will fail with an error if you have duplicates. You can have this error ignored in a few ways. My preferred way is:
INSERT INTO RelationsAuthors (MainId, AuthorId)
VALUES(:MainId, :AuthorId)
ON DUPLICATE KEY UPDATE MainId = VALUES(MainId);
This will specifically ignore duplicate key errors, but other problems will still generate an error (if appropriate). Note I removed the first column. I'm guessing from the syntax that it is an auto-incremented id, so you don't need to include it in the insert statement at all.

LIKE % XX(YY)GG % not working in MySQL

I have used Stored procedure to check whether a name exist in a table or not by using the following code snippet..
BEGIN
IF ids = 0 THEN
SELECT * FROM table_name WHERE `table_id` = alb_id AND name LIKE CONCAT('%',var_name,'%');
END IF;
END
I got the solution if the name doesn't contain any special characters or brackets, like XXXX.
If the name contains any brackets means result not came, like XX(YY)GG.
Suggest me for the best solution
Edited:
In this if a name exist already i should not insert it again, for this condition i used this procedure. If it returns mysql_num_rows > 0 means i wont insert, else i will insert the name into my table..
My sample names are,..
Turning Tables (Live Acoustic)
Hiding My Heart
Someone Like You (Live Acoustic)
Right Now (Na Na Na)
Keep You Much Longer
Someone Like You
In the list of name "Someone Like You" and "Someone Like You (Live Acoustic)" are two different names, i want to identify the name "Someone Like You (Live Acoustic)" is already exist or not..
How do i do?
CREATE TABLE `stack_test` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`text` varchar(100) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB CHARSET=utf8;
INSERT INTO `blur_new`.`stack_test` (`id`, `text`) VALUES ('1', 'run (rabbit) run');
INSERT INTO `blur_new`.`stack_test` (`id`, `text`) VALUES ('2', 'test');
set #a = 'n (rabbit)';
select * from stack_test where text like concat('%',#a,'%');
results in:
1 |run (rabbit) run
So, it works.
check the rest of the conditions in where clause
check how are you passing the value
you might gonna have to check you data types. I have a feeling something is not right there

insert if id does not exist or update table if id exist query?

hi can you help me to make my query update if table if id exist then if not insert it?
here's my query:
if(isset($_POST['submit'])){
$a=$_POST['no1']; $b=$_POST['ans1']; $c=$_POST['det1'];
$d=$_POST['no2']; $e=$_POST['ans2']; $f=$_POST['det2'];
$g=$_POST['no3']; $h=$_POST['ans3']; $i=$_POST['det3'];
$j=$_POST['no4']; $k=$_POST['ans4']; $l=$_POST['det4'];
$m=$_POST['no5']; $n=$_POST['ans5']; $o=$_POST['det5'];
$p=$_POST['no6']; $q=$_POST['ans6']; $r=$_POST['det6'];
$s=$_POST['no7']; $t=$_POST['ans7']; $u=$_POST['det7'];
$v=$_POST['no8']; $w=$_POST['ans8']; $x=$_POST['det8'];
$y=$_POST['no9']; z=$_POST['ans9']; $zz=$_POST['det9'];
$aa=$_POST['no10']; $bb=$_POST['ans10']; $cc=$_POST['det10'];
$sql=mysql_query("insert into bfp_personnel_questions `(`id`,`question_number`,`answer`,`details`) VALUES ('$id', '$a', '$b','$c'), ('$id','$d','$e','$f'), ('$id','$g','$h','$i'), ('$id','$j','$k','$l'), ('$id','$m','$n','$o'), ('$id','$p','$q','$r'), ('$id','$s','$t','$u'), ('$id','$v','$w','$x'), ('$id','$y','$z','$zz'), ('$id','$aa','$bb','$cc')") or die(mysql_error());`
?><script>alert("Successfully Saved.");window.location="pds_1st.php?part=11";</script><?php }
}
Try SQL syntax insert on duplicate key update.
First off, your script screams for prepared statements. You could drastically improve the speed and performance by switching (especially since you're using the obsolete mysql extensions).
I assume that id is a PRIMARY KEY or at least a UNIQUE index. The simplest way to do this is to do INSERT IGNORE, which will try to insert your record and, if they collide, ignores the error and moves on
INSERT INGORE INTO table(col1, col2)
VALUES('1', '2');
If you want to replace the values, you can use REPLACE in later versions of MySQL
REPLACE INTO table(col1, col2)
VALUES('1', '2');
If the key already exists, the row is updated.

Categories