连接表INSERT语句

时间:2012-12-24 14:51:44

标签: php html join phpmyadmin

我有3张桌子。 tbl_info,tbl_trainings和tbl_infotrainings,其中tbl_infotrainings用于连接tbl_info和tbl_trainings。

tbl_trainings接受多个复选框值。 tbl_trainings包含:

+------+-----------+
|  id  |  training |
+------+-----------+

tbl_infotrainings包含:

+------+-----------+---------------+
|  id  |  info_id  |  training_id  |
+------+-----------+---------------+

我的问题是插入新信息时。这是我使用的代码:

用于插入tbl_info的id(工作正常)

$sql3 = "INSERT INTO tbl_infotrainings (info_id) (SELECT id FROM tbl_info)";

用于插入tbl_training的id(有错误)

$sql4 = "INSERT INTO tbl_infotrainings (training_id) (SELECT id FROM tbl_trainings)";

数据库中所需的输出为:

+------+-----------+------------+
|  id  |  info_id  |  training  |
+------+-----------+------------+
|  1   |    1      |     1      |
+------+-----------+------------+
|  2   |    1      |     2      |
+------+-----------+------------+
|  3   |    1      |     3      |
+------+-----------+------------+

以下是完整代码:

if($_POST["Submit"]=="Submit"){
$sql1="INSERT INTO tbl_info VALUES ('NULL', '$fname', '$mname', '$lname', '$street', '$barangay', '$city', '$number', '$month', '$day', '$year', '$status' , '$spouse', '$dependent')";
$result1=mysql_query($sql1);
$sql3 = "INSERT INTO tbl_infotrainings (info_id) (SELECT id FROM tbl_info)";
$result3=mysql_query($sql3);
$sql4 = "INSERT INTO tbl_infotrainings (training_id) (SELECT id FROM tbl_trainings)";
$result4=mysql_query($sql4);
    for ($i=0; $i<sizeof($checkbox);$i++){
$sql2="INSERT INTO tbl_trainings VALUES ('NULL', '".$checkbox[$i]."')";
$result2=mysql_query($sql2);    
}
}

提前致谢。

1 个答案:

答案 0 :(得分:1)

请勿使用'NULL'作为(我假设)AUTO_INCREMENT ID的文字值 - 只需使用NULL关键字。

...
    $sql1 = "INSERT INTO tbl_info VALUES (NULL, '$fname', '$mname', '$lname', '$street', '$barangay', '$city', '$number', '$month', '$day', '$year', '$status' , '$spouse', '$dependent')"; // NULL not 'NULL'
    ...
    $sql2 = "INSERT INTO tbl_trainings VALUES (NULL, '".$checkbox[$i]."')"; // NULL not 'NULL'
...