1

I'm trying to get a system where the array data is changed to match the ID of its entry on another MySQL table. I am getting this from checkboxes on a PHP script.

This is the code

$insertSQL2 = "INSERT INTO test (Testing) VALUES SELECT Course_id FROM courses WHERE Code IN ";
foreach ($_POST['CheckboxGroup1'] as $Q){
    $Q = mysql_real_escape_string($Q);
    $insertSQL2.= "('$Q'), ";
} 
$insertSQL2 = rtrim($insertSQL2, ", ");

I can get the raw data output when I want. e.g. when the four checkboxes are selected, they will be placed in the table in seperate rows (which I require). However when I try to change it to match the code (When the checked box = a code in the table, the id is placed instead of the code) I get the following error.

You have an error in your SQL syntax; check the manual that corresponds to your MySQL      
server version for the right syntax to use near 'SELECT Course_id FROM courses WHERE 
Code IN ('CNMD'), ('EEM')' at line 1

Has anybody got any possible solutions?

1
  • 1
    WHERE CODE IN ('value1','value2','value3') is how it should look Commented May 18, 2012 at 21:54

2 Answers 2

2

INSERT statements can use either VALUES or SELECT syntax. Not both.

You probably want the second:

INSERT INTO test (Testing) 
  SELECT Course_id 
  FROM courses 
  WHERE Code IN ('CNMD', 'EEM') ;
Sign up to request clarification or add additional context in comments.

1 Comment

Have spent hours trying different methods, first time posting on this site. Cant believe it was because of values - select. You are a ledge Thanks
1

You have to make your SQL sentence look like:

SELECT Course_id FROM courses WHERE Code IN ('CNMD', 'EEM')

So you PHP code would need to be something like:

$insertSQL2 = "INSERT INTO test (Testing) VALUES SELECT Course_id FROM courses WHERE Code IN (";
foreach ($_POST['CheckboxGroup1'] as $Q) {
    $Q = mysql_real_escape_string($Q);
    $insertSQL2.= "'$Q', ";
} 
$insertSQL2 = rtrim($insertSQL2, ", ");
$insertSQL2 .= ")";

1 Comment

or you could add $Q to array then implode using comma separator

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.