2

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')" 
2
  • don't you forget to escape your values? Commented Aug 29, 2011 at 10:39
  • The sample code is vulnerable to SQL injection, which is a very serious security risk. To fix this hole, use prepared statements, passing the values as parameters to the statement rather than interpolating them directly into the string. The site you save may just be your own. Commented Aug 29, 2011 at 10:47

3 Answers 3

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much. The syntax is ok and the code is also ok. That's save me a lot of time.
0
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%' 

1 Comment

Thank you, for your help. This code and syntax is very helpfull
0
$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%'" 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.