PHP MySQL数组SELECT,FROM,WHERE

时间:2022-09-18 14:18:40

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.

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

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.

我可以在需要时获取原始数据输出。例如当选中四个复选框时,它们将以单独的行(我需要)放在表中。但是,当我尝试更改它以匹配代码时(当复选框=表中的代码,而是放置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

Has anybody got any possible solutions?

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

2 个解决方案

#1


2  

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

INSERT语句可以使用VALUES或SELECT语法。不是都。

You probably want the second:

你可能想要第二个:

INSERT INTO test (Testing) 
  SELECT Course_id 
  FROM courses 
  WHERE Code IN ('CNMD', 'EEM') ;

#2


1  

You have to make your SQL sentence look like:

你必须使你的SQL句子看起来像:

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

So you PHP code would need to be something like:

所以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, ", ");
$insertSQL2 .= ")";

#1


2  

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

INSERT语句可以使用VALUES或SELECT语法。不是都。

You probably want the second:

你可能想要第二个:

INSERT INTO test (Testing) 
  SELECT Course_id 
  FROM courses 
  WHERE Code IN ('CNMD', 'EEM') ;

#2


1  

You have to make your SQL sentence look like:

你必须使你的SQL句子看起来像:

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

So you PHP code would need to be something like:

所以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, ", ");
$insertSQL2 .= ")";