$query = "INSERT INTO `posts` (title, author, body, tags)
VALUES (`$title`, `$author`, `$body`, `$tags`)
(SELECT * FROM category WHERE name = $category)";
posts and category both are different tables?
If you have variables with the values:
$etitle = somehow_escape($title); ...
INSERT INTO posts
(title, author, body, tags)
VALUES
('$etitle', '$eauthor', '$ebody', '$etags');
If fetching the values from another table:
INSERT INTO posts
(title, author, body, tags)
SELECT title, author, body, tags
FROM category
WHERE ...
You must escape the values -- Think about what would happen if a ' were in the $title!
When using SELECT with INSERT, there is no VALUES cause.
No need for the parens around the SELECT subquery (in this situation).
Related
I'm trying to insert values like this:
$sql = "INSERT INTO daily_food (number, weight, title, price) VALUES ('1', SELECT weight, title, price FROM food where title = '$add_food' LIMIT 1)";
mysqli_query($conn, $sql);
I have database with food which i'm selecting from. I would like to insert that number aswell but code is doing nothing. I'm new in sql so i can't figure out how the code should look.
Just use insert . . . select, values is not necessary:
INSERT INTO daily_food (number, weight, title, price)
SELECT 1, weight, title, price
FROM food
WHERE title = '$add_food'
LIMIT 1;
Im assuming that number is, indeed, a number, so quotes are not needed.
In addition, you should be passing in $add_food as a parameter, something like this:
INSERT INTO daily_food (number, weight, title, price)
SELECT 1, weight, title, price
FROM food
WHERE title = ?
LIMIT 1;
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();
I am an amateur hobbying a video site, where users can submit video urls. Everything works, but now I want multiple categories to be able to be selected for one same video. Categories are stored in seperate tables. I am sure you will understand from the code:
mysql_query("INSERT INTO videos
(title, source, thumb_large, author, email_by) VALUES('$title', '$video_url', '$thumb_url', '$author', '$email') ") or die(mysql_error());
mysql_query("INSERT INTO videos_categories
(category_id) VALUES('$category_name_id') ") or die(mysql_error());
What I want to do is to add another category for the same video ID the tables are both on AUTO INCREMENT synced with each other at the moment:
mysql_query("INSERT INTO videos_categories (category_id) VALUES('$category_name_id_two') ") or die(mysql_error());
The variable is currently registered as:
$category_name_id = mysql_real_escape_string(htmlspecialchars($_POST['category_id']));
And is currently selected through dropdown (select with name: category_id) and it works fine. However, I want to change this ofcourse into select boxes, so mulitple, or upto 3 categories can be selected, instead of having 3 dropdown menus.
I hope you can help me out with this, I am stuck here.
Edit:
I wanted to add that there are three tables, one from which categories are retrieved, one that stores the video_id+category_id which should make at possible to have multiple categories per video, and one with the videos.
Thanks
So you need to change the select box to something like this:
<select name="category_id[]" multiple="multiple">
<!-- Options -->
</select>
...
In backend, After this query:
mysql_query("INSERT INTO videos
(title, source, thumb_large, author, email_by) VALUES('$title', '$video_url',
'$thumb_url', '$author', '$email') ") or die(mysql_error());
Do:
$video_id = mysql_insert_id();
$categories = $_POST['category_id'];
$values = '';
foreach($categories as $category_id) {
$values .= "('$video_id', '$category_id'),";
}
$values = rtrim($values, ',');
$query = "INSERT INTO videos_categories(video_id,category_id) VALUES $values";
mysql_query($query);
Few Suggestions:
Since mysql_* apis are deprecated, please don't use them. Switch to mysqli.
Do the validation and sanitization of the data before using in sql queires.
i have a form where i post the data to mysql. the query should insert the data from the form into table1, but also include data from another table2 where the ID that is send from the form is equal to the ID in table2?
i use the old mysql connection, i know, not the best :-) and php!
hope someone can help, thanks :-)
Martin
think maybe I should give some more info :-)
table1 is called: books
from the form, i have the following value: itemCode, itemQty, ownerID
i have 2 static value: status, type
the values from table2 that must be inserted into table1 is:
title, description, price, frontcover
from table2 the field isbn should be equal to itemCode from form.
here is what i have tried so far:
$bookid=$_POST['itemCode'];
$itemQty=$_POST['itemQty'];
$status='2';
$ownerID = $user->id;
$query="INSERT INTO books (name, description, price, picture, status, ownerID, itemqty, type, studie, isbn) SELECT (title, description, price, frontcover FROM isbnbooks WHERE isbn=$itemCode), $status, $ownerID, $itemQty, '1', '1', $bookid)";
UPDATE:
I have also tried this one here:
$bookid=$_POST['itemCode'];
$itemQty=$_POST['itemQty'];
$status='2';
$ownerID = $user->id;
$data2 = mysql_fetch_array (mysql_query("SELECT * FROM isbnbooks WHERE isbn = $bookid"));
$title = $data2[title];
$description = $data2[description];
$price = $data2[price];
$picture = $data2[frontcover];
$query="INSERT INTO books (name, description, price, picture, status, ownerID, itemqty, type, studie, isbn)
VALUES ($title, $description, $price, $picture, $status, $ownerID, $itemQty, '1', '1', $bookid)";
mysql_query($query) or die("Opps some thing went wrong");
If you have values 'a' and 'b' to go into columns f1 and f2 of table1; and in f3 you want the value of table2.field where table2.id is 123, you can prepare and execute a SQL statement along these lines:
INSERT INTO table1 (f1, f2, f3)
SELECT 'a', 'b', field FROM table2 WHERE id = 123;
Further to seeing the code in your updated question, the problem with your first attempt is that you're trying to mix INSERT ... SELECT with INSERT ... VALUES; sadly they are mutually exclusive. However, you could write instead:
INSERT INTO books (
name,
description,
price,
picture,
status,
ownerID,
itemqty,
type,
studie,
isbn
)
SELECT
title,
description,
price,
frontcover,
:status, -- use prepared statements to prevent SQL injection
:ownerID, -- see http://bobby-tables.com/ for more info
:itemQty,
'1', -- do you really want a string containing a number?
'1',
:bookid
FROM isbnbooks
WHERE isbn=:itemCode;
Your second attempt looks as though it ought to work (although you really should use prepared statements, see above!); what problems are you having with it?
in the absence of code, here's the workflow id recommend:
Form is submitted -> check and sanitize values - > execute lookup query against "table 2" and get your related values -> commit the update query with both form and "table2" data -> on successful update, notify user that their information was processed -> thank them.
Something like this ? :
$data2 = mysql_fetch_array (mysql_query("SELECT * FROM table2 WHERE id2 = '1'"));
$data1 = data2['column2'];
mysql_query("INSERT INTO table1 VALUES('value1','$data2') WHERE id1 = id2);
im using mysql, these are two tables i have:
posts {id, user_id, post, date}
post_tags {id, tag, post_id(references id in post), user_id}
what im trying to do is if the post has a #tag , i insert the intial post in the POSTS table, and the data in the post_tags table, how could i do that simlateanously?
P.S. i already know how to check if a post has a tag!! i just want to undertand, how can insert data into both!! espcially the ID's because they are generated within mysql(autoincrement)!!
You can seperate these two queries and run them after each other. You can use mysql_insert_id() for the last inserted id in an table.
$query = "INSERT INTO posts (id, user_id, post, date)
VALUES (id, user_id, post, date)";
mysql_query($query) or die(mysql_error().$query); // run query
$lastid = mysql_insert_id(); // this will get the last inserted id.
$query = "INSERT INTO post_tags (id, tag, post_id, user_id)
VALUES (id, tag, ".$lastid.", user_id)";
mysql_query($query) or die(mysql_error().$query); // run query