1

我正在尝试获取一个系统,其中数组数据被更改以匹配其在另一个 MySQL 表上的条目的 ID。我从 PHP 脚本上的复选框中得到这个。

这是代码

$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, ", ");

我可以在需要时获得原始数据输出。例如,当四个复选框被选中时,它们将被放置在表格中的单独行中(我需要)。但是,当我尝试更改它以匹配代码时(当复选框 = 表中的代码时,放置 id 而不是代码)我收到以下错误。

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

有没有人有任何可能的解决方案?

4

2 回答 2

2

INSERT语句可以使用VALUESorSELECT语法。不是都。

你可能想要第二个:

INSERT INTO test (Testing) 
  SELECT Course_id 
  FROM courses 
  WHERE Code IN ('CNMD', 'EEM') ;
于 2012-05-18T22:03:23.750 回答
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 .= ")";
于 2012-05-18T21:54:48.393 回答