INSERT with two SELECT statements - php

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'))");

Related

Prepared statement selecting and inserting values from multiple tables into a single table

I'm trying to select values from 2 different tables "actors" , "movies" and insert them into a new table "relationships". I'm using PHP to do this and I'm quite confused about how I can use a prepared statement to do this.
$firstNamesForDb = trim($_POST["firstNames"]);
$lastNameForDb = trim($_POST["lastName"]);
$movieForDb = trim($_POST["movieName"]);
$selectInsertQuery = "INSERT INTO relationships (actorid, movieid) SELECT actors.actorid, movies.movieid FROM actors, movies WHERE actors.first_names = $firstNamesForDb AND actors.last_name = $lastNameForDb AND movies.title = $movieForDb VALUES(?, ?)";
$statement = $db->prepare($selectInsertQuery);
$statement->bind_param("ii", actorid, movieid);
$statement->execute();
Right now I'm getting the error:
Fatal error: Uncaught Error: Call to a member function bind_param() on
bool in D:\Apps\XAMPP\htdocs\iitajax\movies.php:82 Stack trace: #0
{main} thrown in D:\Apps\XAMPP\htdocs\iitajax\movies.php on line 82
With line 82 being $statement->bind_param("ii", actorid, movieid);
How can I resolve this issue?
I think you want:
INSERT INTO relationships (actorid, movieid)
VALUES (
(SELECT actorid FROM actors WHERE first_names = ?),
(SELECT movieid FROM movies WHERE title = ?)
)
Note that this is only safe as long as each of the two subqueries returns just one row - which, presumably, is your intent. Otherwise, you would get error subquery returns more than one row.
A workaround would be to use the insert ... select syntax:
INSERT INTO relationships (actorid, movieid)
SELECT a.actorid, m.movieid
FROM actors a
CROSS JOIN movies m
WHERE a.first_names = ? AND m.title = ?
Be aware of the implications of this syntax though: if there are several actors with the same first name, or several movies with the same title, then all of them will be inserted in the target table.

Inserting data into Table From Multiple table

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

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.

PHP MySQL Insert Query From Multiple Tables into two tables

I've table like this :
tb_users
id, name, pin_number
tb_attendance
pin, date_time, user_id
i've created simple query for tb_attendace like this :
$sql = "INSERT INTO tb_attendance
( pin, date_time)
values
('$PIN', '$DateTime')";
i want to insert colum user_id from tb_users where tb_users.pin_number = tb_attendance.pin
in mysql command i've success run this :
INSERT INTO tb_attendance (pin, date_time, entry_by)
SELECT pin, date_time, tb_users.id
FROM tb_attendance , tb_users
WHERE tb_attendance.pin = tb_users.pin_number
but i don't know how to create this query into php script.
can some one help me to complete the php script ?
I'm not sure why you need both the pin and user id, if you can just use JOIN to get the PIN.
The query that you want looks something like this:
INSERT INTO tb_attendance (pin, date_time, entry_by)
SELECT $PIN, $DATE_TIME, u.id
FROM tb_users u
WHERE u.pin_number = $PIN;
I would advise you to use query parameters, and not to insert the parameter values directly into the SQL string. That is dangerous -- both in terms of creating a SQL syntax error and in terms of security.

INSERT if not exists, else return id

There are some limitations:
Cannot modify database
Columns are not unique
Needs to return last insert id (RETURNING id)
If exists, return existing id
It will be called through our custom db library (the values in select will be as parameters from PHP (?, ?, ?, !))
INSERT INTO tags (name, color, groupid)
SELECT 'test', '000000', 56
WHERE NOT EXISTS (
SELECT text FROM tags WHERE name = 'test' AND groupid = 56
)
RETURNING id
This works - until to the point where i need to get existing id aswell. With this i only get the inserted id.
Is it possible to return the value of SELECT statement if it doesn't insert?
UPDATE:
DO $$
BEGIN
IF NOT EXISTS (
SELECT text FROM tags WHERE name = 'test' AND groupid = 56
)
THEN
INSERT INTO tags (name, color, groupid)
VALUES ('test', '000000', 56) RETURNING id;
ELSE
RETURN SELECT text FROM tags WHERE name = 'test' AND groupid = 56;
END IF;
END
$$
Was testing with this kind of format - however this ends with a few errors:
RETURN cannot have a parameter in function returning void
You can do this using a CTE.
The info cte has the source data, so replace the values there with your placeholders for PHP.
The CTE will return the results from the first half of the union if an existing record exists (so will show old id), and the second half if an insert was performed (so will show the new id).
WITH info (name, color, groupid) AS
(values('test','000000',56)),
trial AS (
INSERT INTO tags(name, color, groupid)
SELECT info.name, info.color, info.groupid
FROM info
WHERE NOT EXISTS (
SELECT * FROM tags t2
WHERE t2.name = info.name AND t2.groupid= info.groupid)
RETURNING id)
SELECT tags.id
FROM tags
INNER JOIN info ON tags.name = info.name AND tags.groupid= info.groupid
UNION ALL
SELECT trial.id
FROM trial;
SQL Fiddle example: http://sqlfiddle.com/#!15/a7b0f/2
Postgres manual page for using CTEs
http://www.postgresql.org/docs/9.1/static/queries-with.html
You can use an IF statement to do this.
IF NOT EXISTS(SELECT text FROM tags WHERE name = 'test')
BEGIN
INSERT INTO tags (name, color, groupid)
VALUES ('test', '000000', 56)
SET #textId = SCOPE_IDENTITY()
END
ELSE
BEGIN
SELECT #textId = ID FROM tags WHERE name = 'test'
END
You have to make necessary changes in above query as per your requirements.
if name is unique:
INSERT INTO `tags` (name, color, groupid) VALUES ('test', '000000', 56)
ON DUPLICATE KEY UPDATE id=LAST_INSERT_ID(id), `name`='test';
SELECT LAST_INSERT_ID();

Categories