INSERT... WHERE NOT EXISTS error - php

I have syntax error with my code
$insert = #mysql_query("INSERT INTO topics (t_title, t_desc, t_pic, t_link, t_date,cat_id)
SELECT '$t_title','$t_desc','$t_pic','$t_link','$t_date','$cat_id'
WHERE NOT EXISTS (SELECT t_link
FROM topics
WHERE t_link = $t_link
)
")or die(mysql_error());
This returns 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 'WHERE NOT EXISTS (SELECT t_link FROM topics WHERE t_link = 'showthread.php?t=120' at line 3
I thought that the problem is with t_link = $t_link
But when i replaced it with normal value , the problem persists.
Any help ?

You missed the FROM on first SELECT
SELECT '$t_title','$t_desc','$t_pic','$t_link','$t_date','$cat_id'
# MISSED HERE FROM ???
WHERE NOT EXISTS

Here solution for FROM CLAUSE, please, check as solution chumkiu's answer, not mine.
create table a ( i int);
insert into a (i )
select 1
from dual
where 1=2;
insert into a (i )
select 3
from dual
where 1=1;
Results

If t_link is has a unique index in the table, you can do:
$insert = #mysql_query("INSERT IGNORE INTO topics (t_title, t_desc, t_pic, t_link, t_date,cat_id)
VALUES ('$t_title','$t_desc','$t_pic','$t_link','$t_date','$cat_id');
The IGNORE keyword tells it to do nothing if the insert would duplicate a unique key constraint.

Related

PHP: Error on Update statement with subquery

I have a page that updates the data of a specific user. The user has position, which is a foreign key. The query update (below) works fine without the position, but with the position I get the following error.
Query :
$queryUpdate = "UPDATE visitorsystem.employee SET idNumber = '$idNumber', name = '$name',
surname = '$surname',
position = 'SELECT positionid FROM visitorsystem.position WHERE positionName LIKE '%$position%'',
email = '$email'
WHERE employeeid = '$empId'";
$resultUpdate = mysqli_query($connection,$queryUpdate)
or die("Error in query: ". mysqli_error($connection));
Error in query: 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 'SELECT positionid FROM visitorsystem.position WHERE
positionName LIKE '%Informat' at line 3
I have tried to work my way around by using inner join as I have seen some solutions given here on stack but nothing has worked. Any Suggestions ?
Subqueries go within regular parens, not quotes, so in a general sense:
SELECT x FROM y WHERE z IN (SELECT z FROM a)
Single and double quotes (by default) are only for string values.

SQL to only insert a new row into MYSQL table if id does not already exist

I have a mysql database table called sales with the columns id | timeStamp | timeString | EAN where I want to insert new values if the ID does not already exist in the table. For example I may want to add:
9997a04fe3f932bf6f8e9d88f4b8dc96 | 0000003082461 | 11:07 (Thu. 22 May. 2014 | 1400716800
to the database table if the id '9997a04fe3f932bf6f8e9d88f4b8dc96' has not already been entered before.
The SQL I have written so far looks like this: (using 1234 as dummy values, there is already a row in the table with and id of 1)
INSERT INTO `sales`(`id`, `timeStamp`, `timeString`, `EAN`) VALUES (1,2,3,4)
WHERE NOT EXISTS (
SELECT `id` FROM `sales` WHERE `id` = '1'
)
Please help me to get this SQL statement working. At the moment this reports a syntax error of:
#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 'WHERE NOT EXISTS ( SELECT `id` FROM `sales` WHERE `id` = 1 ' at line 2
Add unique index to ID column and then use INSERT IGNORE statement
Before the INSERT Statement you need to check whether the data exist or not. If exits just give a message to user data already exist or whatever you want.
Like this
$result = mysqli_query ($con,"SELECT COUNT(id) FROM sales WHERE (id='$id')");
$row = mysqli_fetch_row($result);
$total_records = $row[0];
if($total_records == 0)
{
INSERT INTO sales(`id`, `timeStamp`, `timeString`, `EAN`) VALUES
($id,$timestamp,$timestring,$Ean);
} else
{
--------------Enter-----
------------Error message------
}

Syntax error with IF EXISTS UPDATE ELSE INSERT

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.
¯\(ツ)/¯

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'

Help resolving SQL error that occurs in code but not in SQL workbench

I run this command in SQL Workbench and it returns my desired results, but it return a syntax error in the browser...
$sql = "SELECT
SUBSTRING(`last_name`, 1, 1) AS alpha,
SUBSTRING(`middle_name`, 1, 1) AS subMiddleName,
`idClients`,
`type`,
`first_name`,
`middle_name`,
`last_name`,
`address`,
`primary_number`,
`secondary_number`,
`home_number`,
`office_number`,
`cell_number`,
`fax_number`,
`ext_number`,
`other_number`,
`comments`
FROM `clients`
WHERE `user_id` = 2
AND `is_sub` = 0
AND `prospect` = 1
ORDER BY `last_name`";
Also user_id, is_sub, and prospect are of the INT data type if anyone wants to know. I tried to treat them as strings in the query, but that still didn't help.
this is the error i get
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 'AND prospect = 1 AND type = 'Buyer'' at line 1
You're not showing us the same query, or the relevant PHP code, as nowhere does the above query use the string 'Buyer'.
That said, you may need to escape the column name type with backticks:
AND `prospect` = 1 AND `type` = 'Buyer'

Categories