MySQL insert combo from php var and other table - php

i am trying to insert into my sql table a combination of php variables and 1 row data from another table. ive found examples that are similar but none that have this combination.
OTHERTABLE.liveDate would be where i need the single record from, but i would need to add a condition such as WHERE id='1' from OTHERTABLE
'$navid', '$loginid', '$total', '$where' are not from OTHERTABLE
INSERT INTO myTable (`navid`,`loginid`, `pageDisplayNum`, `whereFrom`, `liveDate`)
VALUES ('$navid', '$loginid', '$total', '$where', 'OTHERTABLE.liveDate')

INSERT INTO myTable (`navid`,`loginid`, `pageDisplayNum`, `whereFrom`, `liveDate`)
select '$navid', '$loginid', '$total', '$where', OTHERTABLE.liveDate
from OTHERTABLE
where OTHERTABLE.id='1'

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

insert records from one table to another

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

only want to insert one row into other table

How do I get this to only insert one row of data, with selected fields inserted into another table by using the reference ?
so far I can only get all of the fields transferred when using the statement in phpmyadmin
$Reference=$_GET['Reference'];
$sql="INSERT INTO Triage (Reference, Forename)
SELECT Reference, Forename from `Instruction` WHERE Reference='$Reference'"
INSERT INTO Table2(LongIntColumn2, CurrencyColumn2)
SELECT LongIntColumn1, Avg(CurrencyColumn) as CurrencyColumn1 FROM Table1 GROUP BY LongIntColumn1;
INSERT INTO prod_detail(prod_name,prod_code) select Name,Zip as data from info_tb where Name="mittal";
Try something like this:
$Reference=mysql_real_escape_string($_GET['Reference']);
$sql="INSERT INTO Triage (Reference, Forename)
SELECT Reference, Forename FROM `Instruction`
WHERE Reference='$Reference' LIMIT 1";

Data from PHP form is inserted into mysql database several times

I'm pretty new in PHP and MYSQL. I've got this form that I use to enter data into a database I created. I add up values from two fields in separate columns and insert the value into a third column (TOTAL_IN). Then I subtract another value (VALUE3) that's in another field from the value in a field in the third column (TOTAL_IN) and put that value in a different column. All these are in the same table. It works just fine, but the problem is that when I open up my database I see that the data has been inserted 20 or 100 times! How can I stop the data from being inserted so many times?
Please note that the submit button was clicked only once.
Here is what I use:
$sql="INSERT INTO $tbl_name (id, date, value1, value2, total_in, value3, value4)
SELECT '','$date','$value1','$value2',('$value1'+'$value2') AS SUM,
'$value3',(('$value1'+'$value2')-$value3) AS SUM
FROM $tbl_name";
$result=mysql_query($sql);
any help?
Thanks in advance!
EDIT::: Here is what my code looks like now after your suggestions:
//From Ruddy's post
$total_in=$value1+$value2;
$value4=($value1+$value2)-$value3;
//From Amit's post
$sql="INSERT INTO $tbl_name(id, date, value1, value2, total_in, value3, value4) VALUES ('', '.$date.', '.$value1.', '.$value2.', '.$total_in.', '.$value3.', '.$value4.')";
$result=mysqli_query($sql);
it works but it still enters the data many times.
$sql="INSERT INTO $tbl_name (id, date, value1, value2, total_in, value3, value4)
VALUES( '', '".$date."', ".$value1.", ".$value2.", ".$value1+$value2.",
".$value3.",".$value1+$value2-$value4.")";
$result=mysql_query($sql);
You need to concatenate the variables in php while writing in the query please see the syntax.
see here
What you were doing was select all the rows of the table and inserting into all.
$sum= $value1+$value2;
$sum2= ($value1+$value2)-$value4;
$sql="INSERT INTO $tbl_name (id, date, value1, value2, total_in, value3, value4) VALUES ('', '$date', '$value1', '$value2','$sum','$value3','$sum2')"
$result=mysql_query($sql);
I hate sums in the statement, so I took them out.
As it is, your query will INSERT as many rows as returned from the SELECT statement! Looks like your SELECT returns as many rows as there are in $tbl_name and you are re-inserting them in the same table!!

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'

Categories