INSERT IF EXIST UPDATE the table using PHP and Stored Procedure - php

I am writing a PHP Code and having problem with conditions of a query. Also if you could tell my how could i accomplish this by using Stored Procedure in Mysql that would be so nice. My task is to run INSERT query if User foreign key don't exist. If User foreign ke is present in the "User_ID" column then update it.But here i can put condition of unique on Column 'User_ID' in database. So no duplicate event will occur from Database.
The following query is showing this error
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'WHEN 23 NOT IN (SELECT User_ID FROM VoiceMail) ELSE UPDATE VoiceMail SET Urg' at line 3
$result=mysql_query("select * from Users",$con);
while($row= mysql_fetch_array($result))
{
$info=getVM($row['Ext'],$ast);
$info[3]=$row['User_ID']; // To insert User_ID from Users table
$query="INSERT INTO VoiceMail (Urgent, New, Old, User_ID)
VALUES ($info[0],$info[1],$info[2],$info[3])
WHEN $info[3] NOT IN (SELECT User_ID FROM VoiceMail)
ELSE UPDATE VoiceMail SET Urgent=$info[0], New=$info[1], Old=$info[2] WHERE User_ID=$info[3]";
if (!mysql_query($query,$con))
{
die('Error: ' . mysql_error());
}
else echo "Database Updated..!";

Is User_Id an unique key? If so, you can use ON DUPLICATED KEY UPDATE
INSERT INTO VoiceMail (Urgent, New, Old, User_ID)
VALUES ($info[0],$info[1],$info[2],$info[3])
ON DUPLICATE KEY UPDATE Urgent=values(Urgent), New=values(New), Old=values(Old)

Just simply query like :
$query="REPLACE INTO VoiceMail (Urgent, New, Old, User_ID)
VALUES ($info[0],$info[1],$info[2],$info[3])";
It will replace values if already exist, insert new if does not exist.
Hopefully it will help

Related

PHP MySQL Insert Query that won't insert if already exists

I've been doing some research and haven't found anything that I've been able to make work, unfortunately, and I think that stems from not understanding the MySQL construct in the examples I've been looking at.
What I'm trying to do is run an insert query, and do a check on values in 3 specific columns to ensure they don't exist, then insert, else do nothing.
My Table is pretty basic: id(int11), user(varchar(45)), label(varchar(255)), agent(varchar(255)), empid(varchar(10)).
My id is my Primary, with Auto increment, and here is my code I currently have that works on inserting, but doesn't have the handling in place for duplicates:
$i = 0;
foreach ($agents as $ag){
$sql = mysql_query("INSERT INTO `pms_users`
(`id`,`user`,`label`,`agent`,`empid`)
VALUES
(NULL, '$user','$group','$labels[$i]','$ag')");
$i ++;
}
The three columns I need to check against are the $user, $group, and $ag.
Add a unique index for (user, label, empid). Then the database won't allow you to create duplicates.
ALTER TABLE pms_users
ADD UNIQUE INDEX (user, label, empid);
If you can only have one row per combination of user, label and agent, you should define them as a unique constraint:
ALTER TABLE pms_users ADD CONSTRAINT pms_users_unq UNIQUE (`user`, `label`, `agent`);
And then let the database do the heavy lifting with an insert-ignore statement:
INSERT IGNORE INTO `pms_users`
(`user`, `label`, `agent`, `empid`)
VALUES ('some_user', 'some_label', 'some_agent', 123)
You can try insert on duplicate key update query.. It checks duplicate keys. If they exist MySQL do update query if not exist MySQL doing insert query.
Sure in your database you should declare unique keys.
Here is MySQL documentation for this case
https://dev.mysql.com/doc/refman/8.0/en/insert-on-duplicate.html

SQL update if exist, insert if not exist not working

I want to update a record if it exists or create a new record if it does not exist yet but somehow it is throwing an error and I cannot find out why..
I want to update the status of a customer if it exists or create a new customer if not exist.
my query:
$sql = "SELECT CASE WHEN EXISTS ( SELECT * FROM sms WHERE number = '123456789' AND customer_id = '1' ) THEN UPDATE sms SET stat = '1' ELSE INSERT INTO sms (number, customer_id, stat) values ('+32485386902', '1', '1') END"
This throws error:
[Err] 1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to
use near UPDATE sms SET stat = '1' ELSE INSERT INTO sms (number, customer_id, stat) value at line 1
However if I change the update and insert into to 1 and 2 it shows 1 if exist, or 2 if not.
Can anyone help me out :) ? Thanks a lot!
adding a second key to the customer_id made this working:
$sqlsms = "INSERT INTO sms (number, customer_id, stat) VALUES('$phone', '$compID', '$smsPromo') ON DUPLICATE KEY UPDATE stat = '$smsPromo'";
In SELECT query you always must have clause FROM. I recommend you first write a SELECT query to know if the record exists, then if the record not exists you can run INSERT else UPDATE. You can't use SELECT * FROM sms in subquerys, it's mistake sixtaxe.

mysql update if some values exists otherwise create a new entry [duplicate]

This question already has answers here:
MySQL 'UPDATE ON DUPLICATE KEY' without a unique column?
(3 answers)
Closed 10 months ago.
I have a table rating with these fields rate_id, game_id, rating, ip. Let suppose that these fields has the following values 1,130,5,155.77.66.55
When a user try to vote for a game, I want with mysql to check if he has already vote for this game so mysql will check if ip and game_id already exists, if they exists then mysql will update the value of rating otherwise will create a new entry.
What is a efficient way to do this?
Create unique index that covers ip + game_id. After that you can use INSERT ... ON DUPLICATE KEY UPDATE statement.
So the total query will be something like
INSERT INTO rating (rate_id, game_id, rating, ip) VALUES (1,130,5,'155.77.66.55')
ON DUPLICATE KEY UPDATE rating = 5
MySQL allows an on duplicate key update syntax for INSERT. So if you set your key to be game_id, user_id (or whichever way you identify the user) then you can use INSERT...on DUPLICATE KEY UPDATE which will do just that:
http://dev.mysql.com/doc/refman/5.5/en/insert.html
You could also take a look at REPLACE INTO. Maybe not for this project but for future reference:
REPLACE works exactly like INSERT,
except that if an old row in the table
has the same value as a new row for a
PRIMARY KEY or a UNIQUE index, the old
row is deleted before the new row is
inserted
from: dev.mysql.com
// check to see if exist
$sql = "SELECT ip FROM rating WHERE ip=$ip && game_id={$game_id}";
$result = mysql_query($sql);
$row = mysql_fetch_assoc($result);
if(isset($row['ip'])){
mysql_query("UPDATE HERE");
}else{
mysql_query("INSERT HERE");
}

PHP: Inserting using sqlsrv pdo using triggers

I'm using sqlsrv pdo driver (used both 5.2 and 5.3 versions) and I'm seeing what I believe is unintended behavior. Hopefully I'm doing something wrong.
I've created 2 tables in sql express 2008. One (Locations) is a table of primary keys shared with other tables. The other table (Rooms) has 2 (or more) columns...a key column linked as a foreign key to the first table and one (or more) data columns. So it looks like:
Locations
LocationID int
1
2
3
4
5
Rooms
LocationID int, Roomname varchar(50)
2, 'living'
4, 'dining'
2,4 both link back to the Locations table.
Then I create a unique constraint on the Roomname column:
ALTER TABLE Rooms ADD CONSTRAINT UniqueRoom UNIQUE (Roomname)
Next, I created an INSTEAD OF INSERT trigger on the Rooms table:
CREATE TRIGGER [dbo].[Rooms_INSERT]
on [dbo].Rooms
INSTEAD OF INSERT
as
BEGIN
INSERT INTO dbo.Locations DEFAULT VALUES
INSERT INTO dbo.Rooms select ##IDENTITY, Roomname from inserted
END
Now I can insert data into the rooms table by:
INSERT INTO Rooms VALUES (null, 'roomname')
I use the sqlsrv PDO object to insert data through PHP:
$db = new PDO("sqlsrv:server=$serverName;Database=db", "", "");
$sql=("insert into Rooms values (null,?)");
$dbobj = $db->prepare($sql);
if($dbobj->execute(array("dining")))
print "<p>insert successful</p>";
else
print "<p>insert unsuccessful</p>";
Starting with the table listing above, I get the following results:
Modify insert statement to "insert into Rooms values (?)" - fails as expected because it expects two args, "insert unsuccessful."
Revert insert statement to normal, attempt to insert array("bedroom") - successful as expected, "insert successful."
Re-attempt insert of array("bedroom") - db insert fails, no entries are made in either table, but attempt is reported successful "insert successful."
Why is the 3rd attempt reported as successful when there were no lasting entries made to the database? Or, more specifically, how can I modify either my PHP or my SQL to properly detect when an insert like this fails due to a violation of a unique constraint?

MySQL - ignore insert error: duplicate entry

I am working in PHP.
Please what's the proper way of inserting new records into the DB, which has unique field.
I am inserting lot of records in a batch and I just want the new ones to be inserted and I don't want any error for the duplicate entry.
Is there only way to first make a SELECT and to see if the entry is already there before the INSERT - and to INSERT only when SELECT returns no records? I hope not.
I would like to somehow tell MySQL to ignore these inserts without any error.
Thank you
You can use INSERT... IGNORE syntax if you want to take no action when there's a duplicate record.
You can use REPLACE INTO syntax if you want to overwrite an old record with a new one with the same key.
Or, you can use INSERT... ON DUPLICATE KEY UPDATE syntax if you want to perform an update to the record instead when you encounter a duplicate.
Edit: Thought I'd add some examples.
Examples
Say you have a table named tbl with two columns, id and value. There is one entry, id=1 and value=1. If you run the following statements:
REPLACE INTO tbl VALUES(1,50);
You still have one record, with id=1 value=50. Note that the whole record was DELETED first however, and then re-inserted. Then:
INSERT IGNORE INTO tbl VALUES (1,10);
The operation executes successfully, but nothing is inserted. You still have id=1 and value=50. Finally:
INSERT INTO tbl VALUES (1,200) ON DUPLICATE KEY UPDATE value=200;
You now have a single record with id=1 and value=200.
You can make sure that you do not insert duplicate information by using the EXISTS condition.
For example, if you had a table named clients with a primary key of client_id, you could use the following statement:
INSERT INTO clients
(client_id, client_name, client_type)
SELECT supplier_id, supplier_name, 'advertising'
FROM suppliers
WHERE not exists (select * from clients
where clients.client_id = suppliers.supplier_id);
This statement inserts multiple records with a subselect.
If you wanted to insert a single record, you could use the following statement:
INSERT INTO clients
(client_id, client_name, client_type)
SELECT 10345, 'IBM', 'advertising'
FROM dual
WHERE not exists (select * from clients
where clients.client_id = 10345);
The use of the dual table allows you to enter your values in a select statement, even though the values are not currently stored in a table.
from http://www.techonthenet.com/sql/insert.php
You can use triggers.
Also check this introduction guide to triggers.
Try creating a duplicate table, preferably a temporary table, without the unique constraint and do your bulk load into that table. Then select only the unique (DISTINCT) items from the temporary table and insert into the target table.
$duplicate_query=mysql_query("SELECT * FROM student") or die(mysql_error());
$duplicate=mysql_num_rows($duplicate_query);
if($duplicate==0)
{
while($value=mysql_fetch_array($duplicate_query)
{
if(($value['name']==$name)&& ($value['email']==$email)&& ($value['mobile']==$mobile)&& ($value['resume']==$resume))
{
echo $query="INSERT INTO student(name,email,mobile,resume)VALUES('$name','$email','$mobile','$resume')";
$res=mysql_query($query);
if($query)
{
echo "Success";
}
else
{
echo "Error";
}
else
{
echo "Duplicate Entry";
}
}
}
}
else
{
echo "Records Already Exixts";
}

Categories