Inserting data into Table From Multiple table - php

I Have a Question in mysql database.
I want to insert some data into a table selected from multiple tables.
This is my query
INSERT INTO dapot_dummy ('site_id','rnc_id','wbts_id','ip3g','vlan','status_vlan')
VALUES (
(SELECT id FROM site WHERE id_site = 'TIM001')
,(SELECT id from rnc where rnc_name = 'RNC Timika-1')
,'117','10.250.46.85','3339',
(SELECT id from status_vlan where status_vlan = 'Metro E'))
which I refer in my previous question link
Here is the output
4 errors were found during analysis.
A comma or a closing bracket was expected (near "SELECT" at position
100) Unexpected token. (near "id" at position 107) This type of clause
was previously parsed. (near "from" at position 163) Unrecognized
statement type. (near "from" at position 163) Query SQL: Dokumentasi
INSERT INTO dapot_dummy
('site_id','rnc_id','wbts_id','ip3g','vlan','status_vlan') VALUES (
(SELECT id FROM site WHERE id_site = 'TIM001') ,(SELECT id from rnc
where rnc_name = 'RNC Timika-1') ,'117','10.250.46.85','3339', (SELECT
id from status_vlan where status_vlan = 'Metro E'))
MySQL menyatakan: Dokumentasi
1064 - You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use
near ''site_id','rnc_id','wbts_id','ip3g','vlan','status_vlan')
VALUES (
(SELEC' at line 1
How to fix it? Please help

Even the sub query must have valid syntax:
INSERT INTO dapot_dummy ('site_id','rnc_id','wbts_id','ip3g','vlan','status_vlan')
VALUES (
(SELECT 'TIM001' FROM site WHERE id_site = 'TIM001')
,(SELECT 'RNC Timika-1' from rnc where rnc_name = 'RNC Timika-1')
,'117','10.250.46.85','3339',
(SELECT 'Metro E' from status_vlan where status_vlan = 'Metro E'))
Hope I hit the tables correctly...
Basically test each sub query on your database to make sure it is valid and you can obtain the data you are expecting, then compose the wide full query..

You should to use '`' backtiks for mark column names instead quotes:
INSERT INTO dapot_dummy (`site_id`,`rnc_id`,`wbts_id`,`ip3g`,`vlan`,`status_vlan`)
VALUES (
(SELECT id FROM site WHERE id_site = 'TIM001')
,(SELECT id FROM rnc WHERE rnc_name = 'RNC Timika-1')
,'117','10.250.46.85','3339',
(SELECT id FROM status_vlan WHERE status_vlan = 'Metro E'))
Also I advice to add LIMIT 1 to sub-queries

Related

Insert new records if column does not contain the values in an array

I have an array of values that I am looping through, trying to check a MySQL table for a column match for the array value, then inserting a new record if no match is found.
foreach($mls_ids as $mls_id) {
$query = "INSERT INTO mdc_data (mls_id) VALUES ('$mls_id')
WHERE NOT EXISTS ( SELECT mls_id FROM mdc_data WHERE mls_id = '$mls_id')
LIMIT 1 ";
$result = mysqli_query($mysqli, $query) or trigger_error("Query Failed!
SQL: $query - Error: ". mysqli_error($mysqli), E_USER_ERROR);
}
No records are inserted into an the table. (the table is empty)
Error thrown: 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 mls_id FROM mdc_data WHERE mls_id
= '2189665') LIMIT
INSERT INTO mdc_data (mls_id)
SELECT * FROM (SELECT '$mls_id') AS tmp
WHERE NOT EXISTS (
SELECT mls_id FROM mdc_data WHERE id = '$mls_id'
) LIMIT 1;
Working code.
Added a unique index on mls_id col (#Dimi).
Used example provided by #Funk Forty Niner for the rest.
$query = "INSERT INTO mdc_data (mls_id)
SELECT '$mls_id' FROM DUAL
WHERE NOT EXISTS (SELECT mls_id FROM mdc_data
WHERE mls_id='$mls_id')
LIMIT 1";
Better understanding of the use of Dual now.
Thanks for the assistance!

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.

INSERT with two SELECT statements

Here is what I am currently trying but I am receiving an mySQL error:
mysql_query ("INSERT INTO profile_tag (profile_id, tag_id)
(SELECT profile_id FROM profile WHERE username = '$username'),
(SELECT tag_id FROM tag WHERE tag = '$music' OR tag = '$sports' OR tag = '$tech')");
I am able to complete an INSERT using a single SELECT statement however, not two.
The error I receive:
Query is invalid: 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 tag_id FROM tag WHERE tag = '' OR tag = 'sports' OR tag = '')' at line 1
Much like the error says, the syntax is incorrect. The values of the insert has to match the number of values in the column definition.
INSERT INTO profile_tag (profile_id, tag_id)
SELECT
profile_id, tag_id
FROM
profile
CROSS JOIN tag
WHERE
username = ?
AND tag IN (?, ?, ?)
Note that this will insert multiple rows if a tag value is found for each of the inputs, but I believe that is what you want.
You can use VALUES clause
insert into profile_tag(user_id, tag_id) values
((select id from users where username = 'alice'),
(select id from tags where tag = 'music'));
http://sqlfiddle.com/#!2/76439/1/0
mysql_query ("INSERT INTO profile_tag (profile_id, tag_id)
(SELECT profile.profile_id, tag.tag_id FROM profile LEFT JOIN tag ON 1 WHERE profile.username = '$username' AND tag.tag IN ('$music', '$sports', '$tech'))");

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.

Count rows in one table within a IF statement

Is it possible to check if num rows in a table is 0 then perform an insert, all in ONE sql statement?
Here's my query that I tried but it says I have a syntax error:
$query =
"IF (SELECT COUNT(ID) FROM votes WHERE userid = $userid AND itemid = $itemid AND itemtype=1) = 0
INSERT INTO votes (itemtype, itemid, userid) VALUES (1, $itemid, $userid)
SELECT 1 AS result
ELSE
SELECT 0 AS result
END IF";
I know the SELECT COUNT bit works successfully on its own.
NO IDEA if this is the best way of solving this, but it will work. Basically, it simply causes an error if the condition is false, and so it prevents insert:
-- make itemtype not nullable then simply insert
INSERT INTO votes SELECT
CASE
WHEN
(SELECT COUNT(ID)
FROM votes
WHERE userid = $userid AND itemid = $itemid AND itemtype=1) = 0 THEN 1
ELSE NULL
END CASE,
$itemid, $userid;
I don't have access to MySQL to test this right now, but would this work?
INSERT INTO votes (itemtype, itemid, userid)
(SELECT 1,$itemid, $userid
WHERE NOT EXISTS (
SELECT *
FROM votes
WHERE itemtype=1
AND itemid=$itemid
AND userid=$userid))

Categories