$sql = "INSERT INTO leave_apply (employee_id, type, start, end, reason, status) VALUES ('$employee_id', '$type', '$start', '$end', '$reason', 'pending'), INSERT INTO schedules (item, date, status) VALUES ('$reason', '$date', 'pending' )";改为正确的语句
时间: 2023-12-24 16:05:36 浏览: 52
在一条SQL语句中,不能同时执行多个INSERT INTO语句,应该将它们分开写成两条独立的SQL语句。修改后的SQL语句如下:
```php
$sql1 = "INSERT INTO leave_apply (employee_id, type, start, end, reason, status) VALUES ('$employee_id', '$type', '$start', '$end', '$reason', 'pending')";
$sql2 = "INSERT INTO schedules (item, date, status) VALUES ('$reason', '$date', 'pending' )";
if(mysqli_query($conn, $sql1) && mysqli_query($conn, $sql2)){
// 执行成功
}else{
// 执行失败
}
```
这样就可以分别向leave_apply和schedules两个表中插入数据了。
相关问题
$sql = "INSERT INTO leave_apply (employee_id, type, start, end, reason, status) VALUES ('$employee_id', '$type', '$start', '$end', '$reason', 'pending'), INSERT INTO schedules (item, date, status) VALUES ('$reason', '$date', 'pending' )";一条语句中操作两个数据表的正确方法
在一条SQL语句中操作多个数据表时,可以使用多条SQL语句,也可以使用MySQL的多表插入语法INSERT INTO ... SELECT ...,具体方法如下:
方法一:
```php
$sql1 = "INSERT INTO leave_apply (employee_id, type, start, end, reason, status) VALUES ('$employee_id', '$type', '$start', '$end', '$reason', 'pending')";
$sql2 = "INSERT INTO schedules (item, date, status) VALUES ('$reason', '$date', 'pending' )";
if(mysqli_query($conn, $sql1) && mysqli_query($conn, $sql2)){
// 执行成功
}else{
// 执行失败
}
```
方法二:
```php
$sql = "INSERT INTO leave_apply (employee_id, type, start, end, reason, status) VALUES ('$employee_id', '$type', '$start', '$end', '$reason', 'pending'),
(SELECT '$reason', '$date', 'pending' FROM dual)";
if(mysqli_query($conn, $sql)){
// 执行成功
}else{
// 执行失败
}
```
在方法二中,使用了MySQL的多表插入语法INSERT INTO ... SELECT ...,dual是MySQL的一个虚拟表,可以在SELECT语句中使用。注意,使用多表插入语法时,每个子查询中的列数和类型必须一致。
阅读全文