Syntax error with IF EXISTS UPDATE ELSE INSERT - php

I'm using MySQL 5.1 hosted at my ISP. This is my query
mysql_query("
IF EXISTS(SELECT * FROM licensing_active WHERE title_1='$title_1') THEN
BEGIN
UPDATE licensing_active SET time='$time' WHERE title_1='$title_1')
END ELSE BEGIN
INSERT INTO licensing_active(title_1) VALUES('$title_1')
END
") or die(mysql_error());
The error is
... check the manual that corresponds to your MySQL server version for the right syntax to use near 'IF EXISTS(SELECT * FROM licensing_active WHERE title_1='Title1') THEN ' at line 1
My actual task involves
WHERE title_1='$title_1' AND title_2='$title_2' AND version='$version' ...ETC...
but I have reduced it down to make things simpler for my problem solving
In my searches on this, I keep seeing references to 'ON DUPLICATE KEY UPDATE', but don't know what to do with that.

Here is a simple and easy solution, try it.
$result = mysql_query("SELECT * FROM licensing_active WHERE title_1 ='$title_1' ");
if( mysql_num_rows($result) > 0) {
mysql_query("UPDATE licensing_active SET time = '$time' WHERE title_1 = '$title_1' ");
}
else
{
mysql_query("INSERT INTO licensing_active (title_1) VALUES ('$title_1') ");
}
Note: Though this question is from 2012, keep in mind that mysql_* functions are no longer available since PHP 7.

This should do the trick for you:
insert into
licensing_active (title_1, time)
VALUES('$title_1', '$time')
on duplicate key
update set time='$time'
This is assuming that title_1 is a unique column (enforced by the database) in your table.
The way that insert... on duplicate works is it tries to insert a new row first, but if the insert is rejected because a key stops it, it will allow you to update certain fields instead.

The syntax of your query is wrong. Checkout http://dev.mysql.com/doc/refman/5.0/en/control-flow-functions.html
Use the on duplicate key syntax to achieve the result you want. See http://dev.mysql.com/doc/refman/5.0/en/insert-select.html

Another solution
$insertQuery = "INSERT INTO licensing_active (title_1) VALUES ('$title_1')";
if(!$link->query($insertQuery)){ // Insert fails, so update
$updateQuery = "UPDATE licensing_active SET time='$time' WHERE title_1='$title_1'";
$link->query($updateQuery);
}

Here is the example I tried and its works fine:
INSERT INTO user(id, name, address) VALUES(2, "Fadl", "essttt") ON DUPLICATE KEY UPDATE name = "kahn ajab", address = "Address is test"

I am amazed to see so many useless codes and answers...
Just replace INSERT with REPLACE.
¯\(ツ)/¯

Related

If inputs exist, dont insert, else insert PHP mysql

I've just started with php, and i wondered if anyone can help.
i have this
$sql="INSERT INTO $tbl_name SET date='$mydate' , event='$myevent'";
$result=mysql_query($sql);
I need to know how to make it see if the event exists, and if it does i need it to do nothing, if it doesn't then insert it!
split it into 2 queries:
1) check if event exists. If yes then do nothing, else insert a new event
2) continue with your query. this way the event will allays exist when inserting your data
This is something that can be done through MySQL alone.
Setup a unique key for the event column by running the following MySQL Command on your table:
CREATE UNIQUE INDEX `i_event` ON `TABLE_NAME_GOES_HERE` (`event`);
For more information: http://dev.mysql.com/doc/refman/5.0/en/create-index.html
Do this for every possible table you expect to see in the $tbl_name variable.
Then, change your PHP Query:
$sql="INSERT IGNORE INTO $tbl_name SET date='$mydate' , event='$myevent'";
$result=mysql_query($sql);
For more information on INSERT IGNORE: http://dev.mysql.com/doc/refman/5.5/en/insert.html
INSERT IGNORE simply does as it states... it will try to insert the row unless it fails validation (in this case from an index that you declared HAS to be unique).
Try:
$query = mysql_query("SELECT $myevent from $tbl_name ")
$rows = mysql_num_rows($query)
if ($num_rows > 0) {
// do nothing
}
else {
$sql = "INSERT INTO $tbl_name SET date='$mydate' , event='$myevent'";
$result = mysql_query($sql);
}
As a sidenote: mysql_ functions are deprecated and it's recommended to switch to mysqli or PDO.

Select and update not working

I have a table viewer with id, ip, date_last_viewed & blog_id as the columns. I'm first checking whether a particular entry having the same IP and blog_id is present or not. If yes, it updates the date. Else, it inserts a new entry.
My code is below:
$search_ip = mysql_query("SELECT ip FROM viewer WHERE ip = '".$_SERVER['REMOTE_ADDR']."' AND blog_id= '".$b_id."' ");
if ($search_ip == false){
$insert_ip = mysql_query("INSERT INTO viewer (ip, blog_id, date_last_viewed) VALUES ('".$_SERVER['REMOTE_ADDR']."', '".$b_id."', NOW())");
}
else {
$update_ip = mysql_query("UPDATE viewer SET date_last_viewed = NOW() WHERE ip = '".$_SERVER['REMOTE_ADDR']."' AND blog_id='".$b_id."' ");
}
The table is not inserting anything. What am I doing wrong here? Also, as I'm new to PHP programming, could someone tell me how to modify the above code to PDO?
You can actually do it in just one query.
MySQL has a special feature called INSERT ... ON DUPLICATE KEY UPDATE which basically insert if the record does not exist or update if it already exists. One thing you need to do is to define a unique column(/s)
INSERT ... ON DUPLICATE KEY UPDATE Syntax
Based on your statement, you need to define a unique constraint on both column,
ALTER TABLE viewer ADD CONSTRAINT vw_uq UNIQUE (ip, blog_id)
and execute this statement,
INSERT INTO viewer (ip, blog_id, date_last_viewed)
VALUES ($_SERVER['REMOTE_ADDR'], b_id, NOW())
ON DUPLICATE KEY UPDATE date_last_viewed = NOW()
As a sidenote, the query is vulnerable with SQL Injection if the value(s) of the variables came from the outside. Please take a look at the article below to learn how to prevent from it. By using PreparedStatements you can get rid of using single quotes around values.
How to prevent SQL injection in PHP?
Assuming your mysql_query executes correctly, it wont return false. What you should do is check the number of rows it returns. You can do this using mysql_num_rows.
Also, take note of the big red warning box at the top of the mysql_* man pages.
You should first add error handlers. Then move to mysqli_ and use prepared statements.
$search_ip = mysql_query( "SELECT ... " ) or die( mysql_error() );
if( mysql_num_rows($search_ip) == 0 ) {
$insert_ip = mysql_query( "INSERT ... " ) or die( mysql_error() );
}
else {
$update_ip = mysql_query( "UPDATE ... " ) or die( mysql_error() );
}
$search_ip will never == false, because it is a reference to the result. Use mysql_num_rows($earch_ip) instead. Also note that mysqli replaces this and your code is actually deprecated
That's not the right way to check if a query returned a value:
$search_ip = mysql_query("SELECT ip FROM viewer WHERE ip = '".$_SERVER['REMOTE_ADDR']."' AND blog_id= '".$b_id."' ");
if (mysql_num_rows($search_ip)==0) {
....
}

MySQL DELETE failing randomly and very infrequently

I have a MySQL DELETE statement followed by an INSERT statement to ensure only one copy of a data set for a given ID. (There is a reason why I do not use UPDATE)
The problem is that I have noticed in a data set spanning 5000+ entries that there are 3 instances where the DELETE statement did not execute, but the INSERT statement did. The end result was duplicate entries for the given IDs.
Below is my code. On execution failure the php script will exit with an error message. It must be my level of experience. Any ideas what the problem could be?
//delete
$query_delete = "DELETE FROM q1_6_list WHERE q_id = '".mysql_real_escape_string($q[qID])."'";
$result = mysql_query($query_delete) or errorReport("Error in query: $query_delete. ".mysql_error());
//insert
$query_insert = "INSERT INTO q1_6_list (q_id, vehicle, quantity) VALUES";
$result = mysql_query($query_insert) or errorReport("Error in query: $query_insert. ".mysql_error());
if (!$result)
errorReport($result);
EDIT
On closer inspection I noticed that I did not add the below code right after $result = mysql_query($query_delete)....
if (!$result)
errorReport($result);
Could this also be required to catch all other error messages, or would mysql_query($query_delete) or errorReport... catch all error occurrences?
Your best bet here is to create a primary key on q1_6_list (q_id):
ALTER TABLE q1_6_list ADD PRIMARY KEY(q_id)
and use MySQLs REPLACE INTO syntax, so lose your delete and your insert becomes:
$query_insert = "REPLACE INTO q1_6_list (q_id, vehicle, quantity) VALUES";
You could simply run insert query only if delete query was successful:
if (mysql_query($query_delete)) {
mysql_query($query_insert);
}

Update query MySQL PHP

im trying to update my table using the following query...
$query = mysql_query("UPDATE `outgoings` (id, user_id, bill, bill_name, bill_description, bill_colour ) VALUES ('$id', '$uid', '$bill', '$billname', '$billdescription', '$billcolour') WHERE id = '$id'") or die(mysql_error());
It returns...
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 '(id, user_id, bill, bill_name, bill_description, bill_colour ) VALUES ('', '8464' at line 1
Ive tried removing ' around my variables and googling for alternative methods but cant seem to figutre out what imdoing wrong?
Use this syntax for update statements:
UPDATE `outgoings` set id = '$id', user_id = '$uid' ... where ...
You got it mixed with insert statement I guess.
It looks like your ID is empty (...VALUES ('',...). Should there be an ID there?
Your $id seems to be empty or not defined yet. Read mysql.error() up to the end.
The update query has different syntax, something like that:
UPDATE `outgoings` SET user_id='$uid', bill='$bill' WHERE id = '$id'

mysql muliple queries in one statement

I've looked around on stackoverflow for a similar question, but haven't found exactly what I was looking for, so here goes. In phpMyAdmin you can have multiple queries in one statement and it executes it for you, eg:'
UPDATE `test` WHERE `test2` = 4;
UPDATE `test` WHERE `test4` = 8;
UPDATE `test` WHERE `test8` = 1;
Now if I try to do something like that in PHP, it doesn't work at all. eg:
$test = 'UPDATE `test` SET `value` = "123" WHERE `test2` = 4;
UPDATE `test` SET `value` = "321" WHERE `test4` = 8;
UPDATE `test` SET `value` = "533" WHERE `test8` = 1;';
mysql_query($test);
Gives and 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 '; UPDATE
test SET value = "123" WHERE test2
= 4; UPDATE test SE' at line 1
Is it even possible to combine, say, multiple queries like above, in one statement? I want to do this in the following situation: (The logic behind this is probably very bad, but I don't have much MySQL experience, so please let me know if there's a better way to do it)
The following loops over a couple of times:
function SaveConfig($name, $value)
{
global $sql_save_query;
$sql = 'SELECT * FROM `config` WHERE `name` = "'.$name.'"';
$res = mysql_query($sql);
if($res)
{
$sql_save_query .= 'UPDATE `config` SET value = "'.$value.'" WHERE `name` = "' .$name. '"; '."\n";
}
else
{
$sql_save_query .= 'INSERT INTO `config`(`id`,`name`,`value`) VALUES("","' .$name. '","' .$value. '"); '."\n";
}
}
Then after the loop finishes it runs:
mysql_query($sql_save_query);
Which gives an 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 '; UPDATE
config SET value = "" WHERE name =
"fcolour2"; UPDATE config SE' at
line 1
Now my other option (in my mind) is to just execute an SQL query after each loop, one query at a time. But wouldn't that be bad/slow/bad practice?
the php API forbids you to issue multiple queries in a single call to reduce the chance of an SQL injection attack to your code (think of what would happen if I passed '; UPDATE users SET admin=1 WHERE username='hacker' to your login script as username). You need to either execute multiple statements, or wrap the logic of your statements into a single statement (which is not possible in your case).
It's not possible to execute multiple queries using mysql_query.
You can perform multiple inserts at once using this syntax:
INSERT INTO table (col1, col2) VALUES (0, 1), (2, 3), (4, 5); -- Insert 3 rows
In general less queries = better but for updates you just have to do them.
The loop you have in your example is indicative of an architectural problem.
If you are dealing with an existing record, pass the primary key - then you don't need the select at all - you can just run an update statement.
If you are dealing with a new record, pass no key - then you know to run an insert statement.
probably you can use INSERT ... ON DUPLICATE KEY UPDATE
INSERT INTO table (a,b,c) VALUES (1,2,3)
ON DUPLICATE KEY UPDATE c=c+1;
Some other useful links
http://dev.mysql.com/doc/refman/5.0/en/replace.html
http://www.mysqlperformanceblog.com/2007/01/18/insert-on-duplicate-key-update-and-replace-into/
$sqls = explode(";",$test);
foreach ($sqls as $key=>$sql) {
if (strlen(trim($sql))>0) {
mysql_query(trim($sql));
}
}

Categories