I have three tables in database:
trips(trip_id(pk), trip_name(unique), user_id(fk))
places(place_id(pk), place_name(unique))
trips_places_asc(trip_id(fk), place_id(fk))
Since, many trips can have many places, I have one junction table as above.
Now, if user insert places to the trip, the places will be added to places table and the trip will be associated with the places in trips_places_asc table.
So, if i write query like:
INSERT INTO places (place_name)
VALUES ('XYZ')
INSERT INTO trips (trip_name)
VALUES ('MyTrip')
Then, How to store trip_id and place_id in Junction or Association table trips_places_asc?
will I have to fire two queries? plz help.
Note: There are many questions on SO like this one and this one. but, none of them have accepted answer or not even an answer. so, plz do not mark as duplicate.
Since you have place_name and trip_name as unique just do as:
insert into trips_places_asc ( trip_id, place_id )
values ( (select trip_id from trips where trip_name = 'MyTrip'),
(select place_id from places where place_name = 'XYZ') );
Or depending what comand you are using to insert (php command I mean) you can return the ids after the inserts and use it to run an insert command with it.
It will be like: (using mysqli* functions )
$query = "INSERT INTO trips (trip_name) values ('MyTrip')";
$mysqli->query($query);
$trip_id = $mysqli->insert_id;
$query2 = "INSERT INTO places (place_name) values ('XYZ')";
$mysqli->query($query2);
$place_id = $mysqli->insert_id;
$query3 = "insert into trips_places_asc ( trip_id, place_id ) ";
$query3 .= " values ($trip_id, $place_id)";
Note, I'm doing this directly from my mind, so maybe you have to adjust some syntax error or be concerned about prepared statements.
EDIT
Though I should add the proper documentation link about this command: http://php.net/manual/en/mysqli.insert-id.php
Related
Bit new to MYSQL and PHP - I have the following code that will create a new record in multiple tables that I have setup however I need to merge the following code together somehow as it creates separate rows instead of one record
$sql .=("INSERT INTO orders (customer_id) SELECT customer_id FROM
customer_details;");
foreach($result as $item){
$mysql_desc = $item['product_description'];
$mysql_mode = $item['delivery_mode'];
$mysql_cost = $item['course_cost'];
$sql .=("INSERT INTO orders(product_description, delivery_mode, course_cost) VALUES('$mysql_desc', '$mysql_mode', '$mysql_cost');");
}
The result I'm getting:
Based on your data I assume that you want to insert the customer id and the values from php into the same record. In this case you need to combine them into the same insert ... select ... statement:
$sql .=("INSERT INTO orders(customer_id, product_description, delivery_mode, course_cost) select customer_id, '$mysql_desc', '$mysql_mode', '$mysql_cost' from customer_details;");
Couple of things to note:
This insert ... select ... statement will insert the same records for all customers in the customer details table. I'm not sure if this is your ultimate goal.
Pls consider the advices made in the comments regarding the old mysql API and the use of prepared statements.
To put this more into what I would expect to happen, something along the lines of - prepare statement, then loop through each item and add in new row...
$insert = $connection->prepare("INSERT INTO orders (customer_id,product_description, delivery_mode, course_cost)
VALUES (?,?,?,?)");
foreach($result as $item){
$customerID = 1; // Have to ensure this is what your after
$mysql_desc = $item['product_description'];
$mysql_mode = $item['delivery_mode'];
$mysql_cost = $item['course_cost'];
$insert->execute([customerID,mysql_desc,mysql_mode,mysql_cost]);
}
Hi I am trying to add records from one table to another, once i have added a 'user' record, the table that is being selected contains rows of available security options, and the table that is being inserted to is the child table for the user, detailing security options.
I cam across this code in an earlier post, which i am sure works nicely, however i am trying to modify it so that the values from statement, includes two parts, one from the select query and one which is the key from the master record.#
This is the original code I found from this site:
INSERT INTO def (catid, title, page, publish)
SELECT catid, title, 'page','yes' from `abc`
And this is what I am trying to do with it:
$sql = "INSERT INTO Link_UserSecurity (UserFk, ModuleFk) values ('".$keys["UserPk"]."', SELECT ModulePk from Global_Modules)";
CustomQuery($sql);
And this is the error I am getting:
INSERT INTO Link_UserSecurity (UserFk, ModuleFk) values ('4', SELECT
ModulePk from Global_Modules)
See screenshot for further detail
Obviously I am not concating the from statement properly, but would appreciate any help?
You can insert the $keys["UserPk"] variable as if it were a constant in the SQL:
$sql = "INSERT INTO Link_UserSecurity (UserFk, ModuleFk) SELECT '{$keys["UserPk"]}', ModulePk from Global_Modules";
Do note that $keys["UserPk"] must be escaped before adding it into the query. In PDO, it would look like this:
$keys["UserPk"] = $pdo->quote($keys["UserPk"]);
$sql = "INSERT INTO Link_UserSecurity (UserFk, ModuleFk) SELECT '{$keys["UserPk"]}', ModulePk from Global_Modules";
Could be a problem related to the double quotes sequence
"INSERT INTO Link_UserSecurity (UserFk, ModuleFk)
values ('". $keys['UserPk']. "', SELECT ModulePk from Global_Modules)";
but you could use also a select insert
"INSERT INTO Link_UserSecurity (UserFk, ModuleFk)
SELECT '" . $keys['UserPk']. "' , ModulePk from Global_Modules)";
Adding only new and unique records from one table to another. Limiting is a good idea to prevent it from timeout. It can be run several times until all the records copied.
First, select the latest record ID from the table to be copied:
SET #lastcopied =
(SELECT
IF(MAX(a.exp_inotech_id)>0, MAX(a.exp_inotech_id), 0) AS lastcopied
FROM
kll_export_to a
WHERE exp_tezgah = 'A2015-0056');
Then, select and add the records to the destination table:
INSERT INTO kll_export_to
(SELECT * FROM
kll_export_from f
GROUP BY f.exp_inotech_id
HAVING COUNT(f.exp_inotech_id) = 1 AND exp_tezgah = 'A2015-0056' AND f.exp_inotech_id > #lastcopied
ORDER BY exp_inotech_id
LIMIT 1000);
Not sure that this is even possible. I am inserting values into two tables at the same time using multi_query. That works fine. One of the tables has an auto increment column and I need to take the last auto incremented number and insert it into the second table so like this: insert into table 1 then take the last inserted number from column X and insert it along with other data into table 2. I have played around with using SELECT LAST and INSERT INTO but so far its just doing my head in. The insert statements looks like this:
$sql= "INSERT INTO tbleClients (riskClientId, riskFacility, riskAudDate) VALUES ('$riskclient2', '$facility2', '$riskdate2');";
$sql .="SELECT LAST(riskId) FROM tbleClients;";$sql .="INSERT INTO tblRiskRegister (riskId) SELECT riskId FROM tbleClients ;";
$sql .= "INSERT INTO tblRiskRegister (riskAudDate, riskClientId, riskSessionId, RiskNewId) VALUES ('$riskdate2', '$riskclient2', '$sessionid', '$risknewid')";
Individually they all produce results but I need it to happen simultaneously. I did toy with the idea of doing them all separately but figure thats not very efficient. Any pointers would be appreciated.
$sql= "INSERT INTO tbleClients (riskClientId, riskFacility, riskAudDate) VALUES ('$riskclient2', '$facility2', '$riskdate2');";
After executing the above query, using mysqli_insert_id(), which gives you the last insert id.
So below query is useless.
$sql .="SELECT LAST(riskId) FROM tbleClients;";
$sql .="INSERT INTO tblRiskRegister (riskId) SELECT riskId FROM tbleClients ;";
You can insert last_insert_id in above query.
Unable to find the relation between above & below query.
$sql .= "INSERT INTO tblRiskRegister (riskAudDate, riskClientId, riskSessionId, RiskNewId) VALUES ('$riskdate2', '$riskclient2', '$sessionid', '$risknewid')";
I have a database of Users and another table for Teachers. Teachers have all the properties as a user but also an e-mail address. When inserting into the DB how can I insert the info, ensuring that the ID is the same for both?
the ID currently is on automatic incrament.
this is what I have at the moment:
$sqlQuery="INSERT INTO user(firstName,lastName,DOB,title,password,classRoomID)
VALUES('$myFirstName','$myLastName','$myDOB','$myTitle','$newPassword','$myClassRoom')";
$result=mysql_query($sqlQuery);
$sqlQuery = "INSERT INTO teacher(email) VALUES ('$myEmail')";
$result=mysql_query($sqlQuery);
thank you!
use MYSQL function LAST_INSERT_ID()
OR php mysql http://ro1.php.net/manual/en/function.mysql-insert-id.php
why to use separate table for teachers. instead, you can have email field with in user table and additional field with flag (T ( for teacher) and U (for user). Default can be a U. This have following Pros.
Will Not increase table size as email would be varchar
Remove extra overhead of maintaining two tables.
Same Id can be used
If you want to have that as separate table then answer you selected is good one but make sure last insert id is called in same connection call.
After the first insert, fetch the last inserted id:
$last_id = mysqli_insert_id(); // or mysql_insert_id() if you're using old code
Or you could expand your second query and use mysql's integrated LAST_INSERT_ID() function:
$sqlQuery = "INSERT INTO teacher(id, email) VALUES ((SELECT LAST_INSERT_ID()), '$myEmail')";
Try this:
$sqlQuery="INSERT INTO user(firstName,lastName,DOB,title,password,classRoomID)
VALUES('$myFirstName','$myLastName','$myDOB','$myTitle','$newPassword','$myClassRoom')";
$result=mysql_query($sqlQuery);
$id = mysql_insert_id();
$sqlQuery = "INSERT INTO teacher(id, email) VALUES (' $id ','$myEmail')";
$result=mysql_query($sqlQuery);
Insert data into two tables & using the same ID
First method
$sqlQuery1 = "INSERT INTO user(firstName,lastName,DOB,title,password,classRoomID) VALUES('$myFirstName','$myLastName','$myDOB','$myTitle','$newPassword','$myClassRoom')";
$result1 = mysqli_query($conn, $sqlQuery1);
$lastID = mysqli_insert_id($conn);
$sqlQuery2 = "INSERT INTO teacher(email, lastID) VALUES ('$myEmail', 'lastID')";
$result2 = mysqli_query($conn, $sqlQuery2);
If the first method not work then this is the second method for you
$sqlQuery1 = "INSERT INTO user(firstName,lastName,DOB,title,password,classRoomID) VALUES('$myFirstName','$myLastName','$myDOB','$myTitle','$newPassword','$myClassRoom')";
$result1 = mysqli_query($sqlQuery1);
$sqlQuery2 = "INSERT INTO teacher(email) VALUES ('$myEmail')";
$result2 = mysqli_query($sqlQuery2);
You can set the Foreign Key in your database table (phpMyAdmin/ MySQL Workbench) to let the Foreign Key follow the Primary Key (ID). Then the data after insert will auto-follow the Primary Key ID.
Example here,
Teachers table set ID - Primary Key
Users table set UserID - Foreign Key (will follow the Teachers table ID)
if you're using MySQL WorkBench, you can refer to this link to set a foreign key.
https://dev.mysql.com/doc/workbench/en/wb-table-editor-foreign-keys-tab.html
Hope I can help any of you.
Though you can use the LAST_INSERT_ID() function in order to get the last insert id, the best approach in this case is to create a column reference to user id table.
teacher
id | user_id | email
So the teacher.id could be anyting, but the user_id column is the real reference to user table.
If you use InnoDB table, you can make the database consistent using Foreign keys
You Should Use A Transaction In MySQL. First insert In One Table And GET LAST_INSERT_ID().
Insert LAST_INSERT_ID() In Second Table.
$sqlQuery="INSERT INTO user(firstName,lastName,DOB,title,password,classRoomID)
VALUES('$myFirstName','$myLastName','$myDOB','$myTitle','$newPassword','$myClassRoom')";
$sqlQuery = "INSERT INTO teacher(LAST_INSERT_ID(), email) VALUES (' $id ','$myEmail')";
$result=mysql_query($sqlQuery);
I'm new to php. So, please forgive me if this seems like a dumb question.
Say i have a MySQL insert statement insert into table (a,b) values (1,2),(3,4),(5,6). table 'table' has a auto increment field called 'id'.
how can I retrieve all the ids created by the insert statement above?
It will be great if i get an example that uses mysqli.
You can't. I would suggest that you maintain your own ids (using guid or your own auto-increment table) and use it when you insert into the table.
But it's possible to get the auto-increment value for the last inserted using LAST_INSERT_ID():
http://dev.mysql.com/doc/refman/5.0/en/getting-unique-id.html
AngeDeLaMort's answer is almost right. Certainly, the most appropriate way to deal with the problem is to insert one row at a time and poll the insert_id or generate the sequence elsewhere (which has additional benefits in terms of scalability).
I'd advise strongly against trying to determine the last insert_id and comparing this the most recent insert_id after the insert - there's just too may ways this will fail.
But...an alternative approach would be:
....
"INSERT INTO destn (id, data, other, trans_ref)
SELECT id, data, other, connection_id() FROM source";
....
"SELECT id FROM destn WHERE trans_ref=connection_id()";
....
"UPDATE destn SET trans_ref=NULL where trans_ref=connection_id()";
The second query will return the ids generated (note that this assumes that you use the same connection for all 3 queries). The third query is necessary because connection ids to go back into the pool when you disconnect (i.e. are reused).
C.
In some cases, if you have another identifier of sort such as a UserID, you could filter your query by UniqueID's greater than or equal to mysql_insert_id(), limit by the number of affected rows and only display those by the user. This would really only work inside of a transaction.
$SQL = "INSERT INTO Table
(UserID, Data)
VALUES
(1,'Foo'),
(1,'Bar'),
(1,'FooBar')";
$Result = mysql_query($SQL);
$LastID = mysql_insert_id();
$RowsAffected = mysql_affected_rows();
$IDSQL = "SELECT RecordID
FROM Table
WHERE UserID = 1
AND RecordID >= '$LastID'
LIMIT '$RowsAffected'";
$IDResult = mysql_query($IDSQL);
as a follow up to AngeDeLaMort:
You could seperate your inserts and do it something like this:
$data = array (
array(1,2),
array(3,4),
array(5,6)
);
$ids = array();
foreach ($data as $item) {
$sql = 'insert into table (a,b) values ('.$item[0].','.$item[1].')';
mysql_query ($sql);
$id[] = mysql_insert_id();
}
Now all your new id's are in the $id array.
Maybe I can do this
$insert = "insert into table (a,b) values (1,2),(3,4),(5,6)";
$mysqli->query($insert);
$rows_to_be_inserted=3;
$inserted_id = $mysqli->insert_id // gives me the id of the first row in my list
$last_row_id = ($inserted_id+$rows_to_be_inserted)-1;
$mysql->query("select * from table where id between $inserted_id and $last_row_id");
what to you guys say?