I am writing a recipe database app and I have the database schema sorted but I am not struggling to figure out what query to write to insert the recipe into the database.
I have 3 tables
ingredients
ingredients_id...
recipes
recipe_id ...
recipes (pivot table)
ingredients_id
recipe_id
but it was my understanding that you can only insert data into one table at a time.
This is where my problem lies. If I have a form to input a recipe how do I add the recipe which is split over 3 tables? Do i use multiple queries. If so how can I guarantee they will match.
Sorry if this sounds like a dumb question but it is frying my brain, thanks in advance for the feedback.
Best regards
You guarantee the rows are related to one another by assigning common values to the appropriate columns.
If you have decided to define the recipe_id column in recipes to be AUTO_INCREMENT, and you insert a row which has a generated value assigned to that column, you can use the LAST_INSERT_ID() function to retrieve the value assigned to the column
INSERT INTO recipes (recipe_id, col2, col3) VALUES (NULL, 'fee', 'fi');
If the insert statement succeeded, you can retrieve the value assigned to recipe_id column (in the same MySQL session, before you execute any other statements), by executing a statement like this:
SELECT LAST_INSERT_ID() AS recipe_id;
NOTE: Some MySQL client libraries have methods/functions that perform this for you, so you can retrieve the value without having to prepare and execute another SQL statement in your code, e.g.
PDO::lastInsertId ref: http://www.php.net/manual/en/pdo.lastinsertid.php
mysqli::$insert_id ref: http://www.php.net/manual/en/mysqli.insert-id.php
You could then supply the value returned in the INSERT to the association table, for example
INSERT INTO recipe_ingredient (recipe_id, ... ) VALUES ( 42, ... )
Related
I have two different Databases, names:
dbtest: Table 1
dbtest2: Table 2
I want to select all the data and new entries from dbtest Table 1 to dbtest2 Table 2.
I have tried this
$sqlfin = "INSERT INTO dbtest2.Table2 SELECT * FROM dbtest.Table1";
$resultfi = mysqli_query($db_conn, $sqlfin);
But no luck so far. How can I assure that new Records are insert into both table ? Any help would be appreciated?
lets try it in this format
INSERT INTO `dbtest2`.`Table2` SELECT * FROM `dbtest`.`Table1`
The following conditions hold for INSERT ... SELECT statements:
Specify IGNORE to ignore rows that would cause duplicate-key violations.
AUTO_INCREMENT columns work as usual.
To ensure that the binary log can be used to re-create the original tables, MySQL does not permit concurrent inserts for INSERT ... SELECT
statements (see Section 8.11.3, “Concurrent Inserts”).
To avoid ambiguous column reference problems when the SELECT and the INSERT refer to the same table, provide a unique alias for each
table used in the SELECT part, and qualify column names in that
part with the appropriate alias.
INSERT ... SELECT Syntax
Create Trigger: for adding new entries
CREATE TRIGGER copy_record BEFORE INSERT ON dbtest.Table1
FOR EACH ROW
BEGIN
INSERT INTO dbtest2.Table2 (first_name, last_name) VALUES (new.first_name, new.last_name);
END
trigger_event indicates the kind of operation that activates the
trigger. These trigger_event values are permitted:
INSERT: The trigger activates whenever a new row is inserted into the table; for example, through INSERT, LOAD DATA, and REPLACE
statements.
UPDATE: The trigger activates whenever a row is modified; for example, through UPDATE statements.
DELETE: The trigger activates whenever a row is deleted from the table; for example, through DELETE and REPLACE statements. DROP TABLE
and TRUNCATE TABLE statements on the table do not activate this
trigger, because they do not use DELETE. Dropping a partition does not
activate DELETE triggers, either.
CREATE TRIGGER Syntax
Try this query for your desired task :
Query First (Create Table exactly same like in old database, if you have not):
CREATE TABLE dbtest2.Table2 LIKE dbtest.Table1;
Query Second (Insert all data to newly created table) :
INSERT INTO dbtest2.Table2 SELECT * FROM dbtest.Table1;
Your query looks correct but will fail if the 2 tables have a different structure. Specify the columns to avoid it like:
INSERT INTO dbtest2.Table2 (2_col_1, 2_col_2) SELECT 1_col_1, 1_col_2 FROM dbtest.Table1
With PDO (kind of alternative answer, I don't know much for Mysqli):
You could connect to Mysql with PDO without giving a database name when working with multiple ones (but this isn't mandatory), like:
$db = new PDO( "mysql:host=" . $host . ";", $user, $password, $options );
Then write the Database names, tables and columns like when making a JOIN (as you did): separated by a .
// an example ..
$useDb = $db->query("INSERT INTO db_1.table1 (value_1, value_2) SELECT value_3, value_4 FROM db_2.table2 WHERE db_2.table2.id = 5");
(example tested and working fine)
INSERT INTO dbtest2 (
id,
name,
status )
SELECT id,
name,
'1'
FROM dbtest
ORDER BY id ASC
You can use INSERT...SELECT syntax. Note that you can quote '1' directly in the SELECT part.
I want to insert data partially from select statement..
For example..
I have one table named movie..here's the fields :
-id_movie
-tittle
-studio
-time
And another table named reservation.. here's the fields :
-id_reservation
-tittle
-studio
-time
-seat_1
-seat_2
So, I want to insert value of tittle, studio, and time into reservation table that getting from select statement from movie table. But I'm a little bit confuse about another field in reservation table (id_reservation, seat_1, seat_2).. They're actually don't exist in the first table (movie table)
so how to write the query?
any simple example would be very helpful
thank you
$query = "INSERT INTO reservation(tittle,studio,time)
SELECT tittle,studio,time FROM movie";
INSERT INTO reservation (
tittle,
studio,
time
)
SELECT tittle,
studio,
time
FROM movie;
But you better not have NOT NULL on the columns you leaving without values.
If you want mysql query then:
"INSERT INTO reservation(tittle,studio,time)
SELECT tittle,studio,time from movie";
First do a SELECT from "movie" to obtain the fields you need from that table.
You will have the fields you need stored in 3 variables, say $title, $studio, $time.
As per the table reservation, the field id_reservation should be the PK so set it to autoincrement. You don't have to insert that value as it does it automatically in every insert.
The fields seat_1 and seat_2 will depend on other facts than the data you get from the first table. You should obtain the free seats (I guess there is another table with the total amount of seats), and select 2 using some kind of logic (for example, that they are next to each other)
So in the end, the INSERT query for the table reservation should look like
"INSERT INTO reservation (title, studio, time, seat_1, seat_2) VALUES('$title', '$studio', '$time', $seat_1, $seat_2)");
I have a basic data structure for storing recipes. It consists of three tables as below:
Table 1 - Recipes (recipe_id, recipe_name)
Table 2 - Ingredients (ingredient_id, ingredient_name)
Table 3 - Recipe_Ingredients (recipe_id, ingredient_id)
I have come across a problem when adding a new recipe and would like to know the best practice for inserting.
Currently, on submitting the form I insert into the Recipes table, the recipe_id is auto generated. I then insert into the Ingredients table, again the ingredient_id is auto generated. The third step on submit is to then insert into the Recipe_Ingredients table, but how do I get the values of the recipe and ingredient ids that have just been created in order to insert them into the Recipe_Ingredients table?
I currently have separate PHP functions to insert into the Recipes and Ingredients tables.
You have to get the inserted id value after each insert operation.
The function to get the last insert id is: mysql_insert_id()
mysql_insert_id() will give you the auto generated id of the rows you just inserted
After each insert, do mysql_insert_id() I think, so it gets back the inserted id of the previous insert.
what am doing is clonning an old database to new one with different structure but should have same old data
is it possible to do an insert into insert that return id of the insert query
INSERT INTO tab1 (nom,id_2) VALUES
("jack",(INSERT INTO tab2 (pass) VALUES ("1234")));
in INSERT INTO tab2 (pass) VALUES ("1234") i want to get the id of the insert
but no luck!! (i want it in one sql query (i already know about mysql_insert_id) )
thanks in advance
You cant do this on a single query - use mysql_insert_id() to get the last inserted id for example :
mysql_query('INSERT INTO tab2 (pass) VALUES ("1234")');
$lastid = mysql_insert_id();
mysql_query('INSERT INTO tab1 (nom,id_2) VALUES ("jack",'.$lastid.')');
insert id can be retrieved in mysql as well, so here is a version with no PHP involved (it however performs 2 queries)
INSERT INTO tab2 (pass) VALUES ("1234");
INSERT INTO tab1 (nom,id_2) VALUES("jack",LAST_INSERT_ID());
Lock the table, insert, select max(id), unlock table. This is the only way outside creating your own sequence tables like in postgres if you are adverse for some reason to the last insert id functions. This approach however is going to be like pouring tar into a blender if your table is moderate to high writes.
You can't do this as a single insert because inserts are atomic that is, the ID isn't determined until the statement completes.
Wrap both statements in a transaction and you will get your ID, and atomicity.
I have two tables. One table is meant to serve as a transaction history and the other is a log of member details. When a report is run, I want to move pieces of the member details into the transaction history but ALSO update some field records which would not otherwise exist.
Is it possible to select all records which meet a specific criteria, insert only pieces of the matching row into another table AND update other fields in a single query?
For example:
In table 2, i have member name, date registered, and memberid. I want to move the above records into table 1 but also update the field (status) equal to 'processed'.
Note: I am also using php and pdo to connect to a mysql database.
Is this possible within a single query?
You didn't specify whether the rows you want to update are the same as the ones you are inserting. I am assuming they are:
insert into table1
(member_name, date_registered, memberid, status)
select member_name, date_registered, memberid, 'processed'
from table2
where SomeField = MyCriteria
After much consideration - I decided to use ircmaxell's advice and simply run multiple queries. It ends up not only making things easier but allows me to customize my sorting much easier.
As he said above, "Don't get caught in the trap of less is always better"
Yes:
SELECT *, "processed" INTO table2 FROM table1
You will have to adapt based on the table structures, perhaps even write out all the fields:
SELECT field1, field2, field3, "processed" INTO table2 FROM table1
Of note, this assumes you want to write into table 2 including the processed variable (Might I suggest a boolean?) if you want the "Processed" in the other table it will get more complicated.
Edit: Apparently mysql doesn't support select into so...
INSERT INTO table2 SELECT field1, field2, field3, "processed" FROM table1
Redfilters code works