mdakic
mdakic

Reputation: 186

How to use INSERT...SELECT to insert data form one table to another based on form input

I have situation when i want to add data from column formCompany, formPlace in tabel1 based on input from form into table2 column formCompany, formPlace. Something like this:

$formCompany = $_POST['formCompany'];

$formPlace = $_POST['formPlace'];

$formOffer = $_POST['formOffer'];


$sql="INSERT INTO table2  (formCompany, formPlace, formOffer) values ("SELECT table1.formCompany, table1.formPlace from table1 where formCompany LIKE '%$formCompany%' AND formPlace LIKE '%$formPlace%'", '$formOffer')"

Upvotes: 2

Views: 489

Answers (3)

Johan
Johan

Reputation: 76753

First off

Fix the SQL injection hole
Use PDO, or

$formCompany = mysql_real_escape_string($_POST['formCompany']);
$formPlace = mysql_real_escape_string($_POST['formPlace']);
$formOffer = mysql_real_escape_string($_POST['formOffer']);

The syntax for insert select does not include the keyword 'VALUES'

$sql="INSERT INTO table2  
      (formCompany, formPlace, formOffer) 
      SELECT table1.formCompany, table1.formPlace, '$formOffer' "
        //All insertions happen here ^^^^^^^^^^^^^^^^^^
      ." FROM table1 
        WHERE formCompany LIKE '%$formCompany%' 
          AND formPlace LIKE '%$formPlace%' ";

Now it should work.

Upvotes: 1

genesis
genesis

Reputation: 50982

$sqlSelect="SELECT table1.formCompany, table1.formPlace from table1 where formCompany LIKE '%$formCompany%' AND formPlace LIKE '%$formPlace%'";

fetch it and use it in your INSERT query

or

$sql="INSERT INTO table2  (formCompany, formPlace, formOffer) SELECT table1.formCompany, table1.formPlace, '$formOffer' from table1 where formCompany LIKE '%$formCompany%' AND formPlace LIKE '%$formPlace%'"

Upvotes: 0

Vladimir
Vladimir

Reputation: 846

INSERT INTO table2 (fromCompany, fromPlace, fromOffer) SELECT table1.fromCompany, table1.fromPlace, '$fromOffer' AS t1fromOffer FROM table1 WHERE table1.formCompany LIKE '%$formCompany%' AND table1.formPlace LIKE '%$formPlace%'

Upvotes: 0

Related Questions