insert multiple records with one ID in single query - php

Hello i want insert data into 2 different tables.
First table 'Events:'
id,
name,
desc,
date
Second table 'Events_sub_cat:'
id,
event_id,
name,
desc,
date
I want to insert 2 different data in one query like:
INSERT INTO Events (name, desc, date) VALUES ('name', 'desc', 'date')
INSERT INTO Events_sub_cat (event_id, name, desc, date) VALUES (event_id, 'name', 'desc', 'date')
And i want get in the same query the ID of the even what i just inserted in table 'Events'
to let know to another INSERT what is the 'event_id'

There you go a suggestion:
Insert records into two table at once
As said in the post, there's no way to insert without using mysql_insert_id()

functions such as lmysql_insert_id() return the last inserted id.

you can select the last id from Events and put it in the second insert

Related

How do I combine these two queries into a single INSERT INTO?

Can someone tell me how can I combine these two queries into a single INSERT INTO query?
$query1 = "INSERT INTO `monthly_income`(`Year`, `Month`) VALUES (2017, 'September')";
$query2 = "INSERT INTO `monthly_income`(`totalincome`) SELECT SUM(Income) FROM `eventincome` WHERE eventDate BETWEEN '2017-09-01' AND '2017-09-30'";
Here I want to insert all those values into a single row in the table "monthly_income". In Query2, i generate the total income between two dates from a seperate table called "eventincome". The "monthly_income" table has columns [Year, Month, totalincome]. And the "eventincome" table has columns [eventDate, eventTitle, Earnings, Expenses, Income]. So how can I join these two querys to use it in a
mysqli_query($conn, parameter)
:)
PS: I want to set those values from those queries in the same row, without creating two seperate rows becuse of those two INSERT INTO's. That's why I wanna join/combine/merge(whatever) those two queries :)
Give this a try
$query2 = "INSERT INTO `monthly_income`(`totalincome`,`Year`, `Month`) SELECT SUM(Income),2017 as Year, 'September' as Month FROM `eventincome` WHERE eventDate BETWEEN '2017-09-01' AND '2017-09-30'";
Add the values from the first query as constants in the second query...
"INSERT INTO monthly_income(Year, Month,totalincome) SELECT 2017, 'September',SUM(Income) FROM eventincome WHERE eventDate BETWEEN '2017-09-01' AND '2017-09-3'";

Save data from a php page into 2 sql table

Good day!I really need your help guys. Can someone teach me what statements I need to save data into 2 tables. I have 2 tables namely sales and sales_item. The relationship bet. them is the srfno where in sales table it is the PK, so in sales_item table it is the FK. My php form has srfno, date, clientid, clientname, address, contactperson, contactno, returnreason, explanation, refno; these data should be saved in sales table which I already did and it's working brilliantly. My problem now is that qty, serial, desc also include in the form but these should be saved in sales_item table. When I execute the page, it saves the data in sales table and the qty, serial and desc can't save to sales_item table and it didn't get the srfno from sales table.
here's my code for saving qty, serial and desc to sales_item table which is being ignored by my sql statement when saving.
$retitem= "Select `srfno` from sales_item";
$psql= mysql_query($retitem,$con);
$reti = mysql_num_rows($psql);
$reti = $reti + 1;
while($return = mysql_fetch_assoc($psql))
{
if(isset($return['srfno']))
{
$srfno=$return['srfno'];
}
}
$addretex="Insert into `sales_item` (`sitemid`,`srfno`, `retqty`, `retdesc`,`retserial`, `exqty`, `exdesc`,`exserial`,)
VALUES (' ','$srfno', '$qty', '$desc', '$serialno', ' ', ' ', ' ')";
$ret=mysql_query($addretex);
easily you can use LAST_INSERT_ID to insert your last 3 values into table sales_item with related sales id.
INSERT INTO sales (srfno,date,clientid,clientname,address,contactperson,contactno, returnreason,explanation,refno)
VALUES('value1', 'value2','','',...);
INSERT INTO sales_item (sales_id,qty,serial,desc) //sales_id is foreign key came from sales table and its value will be insert automatically by using LAST_INSERT_ID.
VALUES(LAST_INSERT_ID(),'value_1', 'value_2','value_3');
Before Inserting into 'sales_item', you need to check whether $srfno has valid value using
echo "srfno=".$srfno;exit;
if not, you can easily get value of $srfno after inserting into sales table, just do following after inserting into sales table
$srfno=mysql_insert_id();
You can also check error of insert query of sales_item by mysql_error function
mysql_query($addretex) or die("$addretex ".mysql_error());

Problems with MySQL Complex Insert (Mutli Row Insert with Sub Select)

I'm having an issue with the following query. With the query I'm attempting to insert a row into the notification table for each user who matches the sub select for the recipient id field.
The query I have is as follows, but is not working:
INSERT INTO
notification (type,
target_id,
sender_id,
recipient_id,
data,
timestamp,
is_unread)
('post',
'$id',
'$senderId',
(SELECT user_id FROM group_member WHERE group_id = '$id'),
'1',
'$timestamp',
'1')
I also tried using VALUES prefixed to the information I am attempting to insert, but I read somewhere that for multi row inserts you're supposed to exclude it and just use the values in parenthesis as I have above?
Assuming your variables are properly escaped, you can do
INSERT INTO
notification (type,target_id,sender_id,recipient_id,
data,`timestamp`,is_unread)
SELECT 'post', '$id','$senderId',user_id, '1','$timestamp', '1'
FROM group_member WHERE group_id = '$id'

Access last row added to table - PHP

I have a simple sql query adding a new row to a database and need it to return the a field back to Javascript. The field does Auto_increment but stupildy I called it 'itemId' so mysql_insert_id doesnt work and I don't think I have time to go and amend all the php files that use 'itemId'
Here's my code if it helps:
$addMainItem = "INSERT INTO newsItems (itemId, title, date, tags, location, latitude, longitude, visibleFrontpage, introText, fullDome, liveEvent, customServing, visitorAttraction, retail, digitalCinema, visiblePublic, thumbPath, links, smallDesc) VALUES ('','$title','$date','$tags','$loco','$lat','$long','$visiFront','$intro','$dome ','$live','$custom','$attrac','$retail','$cinema','$public','$thumbPath','$links','$smallDesc')";
$result = mysql_query($addMainItem) or die('error '.mysql_error());
if($result) echo (mysql_insert_id());
I've never heard that naming a column itemId breaking mysql_isert_id().
But you can just select the last inserted record if auto_increment is working.
SELECT * FROM newsItems ORDER BY itemId DESC LIMIT 1
You can put the select statement into a transaction with the insert statement if you're using innoDB and you're worried about a race condition.
mysql_query("SELECT LAST_INSERT_ID()");
Isn't it what are you looking for?

inserting data into two tables?

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

Categories