PHP: Error on Update statement with subquery - php

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.

Related

Trying to make two sql queries, but always landing with error

$query=mysqli_query($conn,"INSERT INTO bus_info(bus_id,route_num,school_name) values('$BusNum','$RouteNum','$SchoolName'); INSERT INTO bus_loc(bus_id,lat,lon) values ((SELECT bus_id from bus_info where bus_info.bus_id='$BusNum'),'$latitude','$longitude')");
PHP
$BusNum = $_POST["BusNum"];
$SchoolName = $_POST["SchoolName"];
$RouteNum = $_POST["RouteNum"];
$latitude = $_POST["lat"];
$longitude = $_POST["lng"];
Database is connected i.e. returned true.enter code here
Fails with :
Error sending data:
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 INSERT INTO bus_loc(bus_id,lat,lon) values ((SELECT bus_id from bus_info where b at line 1
From: http://php.net/manual/de/mysqli.query.php#87203
mysqli::query() can only execute one SQL statement.
Use mysqli::multi_query() when you want to run multiple SQL statements within one query.
How to use mysqli_multi_query: http://php.net/manual/de/mysqli.multi-query.php
For better understanding split query into two parts and use them like :-
$query = mysqli_query($conn,"INSERT INTO bus_info (bus_id,route_num,school_name) values('$BusNum','$RouteNum','$SchoolName')");
$query2 = mysqli_query($conn,"INSERT INTO bus_loc (bus_id,lat,lon) values ((Select bus_id from `bus_info` where bus_id = '$BusNum'),'$latitude','$longitude')");
This query is missing a where clause condition
SELECT bus_id from bus_info where b
change it to like:
SELECT bus_id from bus_info where b = 'something'
but you should not execute two queries like this but execute this first save the result in a variable and then execute the next one like
$query = SELECT bus_id from bus_info where b = 'something'
$saved = $mysqli_query($yourconnection, $query);
$row = mysqli_fetch_assoc();
$fetched = row['columnnamehere'];
and then
INSERT INTO bus_loc(bus_id,lat,lon) values ('$fetched');

Prevent duplicates being added to database table via PHP form

I want to log what a user enters into a PHP form, and make sure they are not entering data that already exists in a database table.
I have the code already that enters the data into the table from user input, but I'm not sure how to check for duplicates. For example I want to check that there is no product under the same name being added again.
$sql = "
INSERT INTO user_date
SELECT
product_name = '$_POST[product_name]'
,code = '$_POST[code]'
,comments = '$_POST[comments]'
WHERE
NOT EXISTS(SELECT * FROM user_data WHERE product_name = '$_POST[product_name]') ";
But I get an error:
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 '= 'fdgfdg' code = 'fdgdfg' WHERE NOT EXISTS(SELECT *' at line 4
I'm aware of the security issues. Its not a live system but just to learn from it.
If you don't want to have duplicate insert then use IGNORE at end of insert statement
$sql = "
INSERT INTO user_date
values
('$_POST[product_name]'
,'$_POST[code]'
,'$_POST[comments]')
ON DUPLICATE KEY IGNORE";
So this way might help you
$result = mysql_query("SELECT * FROM user_data WHERE product_name = '$_POST[product_name]'");
$num_rows = mysql_num_rows($result);
if ($num_rows > 0) {
// do something
}
else {
// do something else
}

INSERT... WHERE NOT EXISTS error

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.

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