繁体   English   中英

如何在单个查询中将 6 倍的值插入到 mysql 表中

[英]how can i insert 6 times value into mysql table in single query

我曾命名为表subject 。我不得不列id (PK), subject_nametotal_classattendence ,和cnic (FK)。 我的用户填写表单并提交。 我通过表单的 post 方法获得了值。 在形式上,我有6个科目及各科我有total_classattendencesubject_name 这是我的代码

if($_SERVER['REQUEST_METHOD']=='POST')
{

    $form=$_POST[form'];
    $s1=$_POST['sub1'];
    $s1=$_POST['sub2'];
    $s1=$_POST['sub3'];
    $s1=$_POST['sub4'];
    $s1=$_POST['sub5'];
    $s1=$_POST['sub6'];
    $month=$_POST['month'];

    $total_attend_1=$_POST['Ts1'];
    $total_attend_2=$_POST['Ts2'];
    $total_attend_3=$_POST['Ts3'];
    $total_attend_4=$_POST['Ts4'];
    $total_attend_5=$_POST['Ts5'];
    $total_attend_6=$_POST['Ts6'];

    $attend_1=$_POST['Attend_s1'];
    $attend_2=$_POST['Attend_s2'];
    $attend_3=$_POST['Attend_s3'];
    $attend_4=$_POST['Attend_s4'];
    $attend_5=$_POST['Attend_s5'];
    $attend_6=$_POST['Attend_s6'];
    $query=mysql_query("INSERT INTO subject VALUE( '','$s1','total_attend_1','$attend_1','$form','$month')") or die(mysql_error());
    /*My query should be here.Should I write 6 insert queries?*/

我已经尝试过使用

foreach($array as $attendee){
}

但没有得到我的任务? 有人可以帮帮我吗?

正确的插入语法是

insert into subject values (sub1, ts1, attend_s1);

或具有多个值

insert into subject values (sub1, ts1, attend_s1), (sub2, ts2, attend_s2), (...);

我猜你想要这样的东西:

function x($str) {return mysql_real_escape_string($str);} // shorter function name
$rows = Array();
for( $i=1; $i<=6; $i++) {
  $rows[] = "(null,'".x($_POST['sub'.$i])."','".x($_POST['Ts'.$i])."','".x($_POST['Attend_s'.$i])."','".x($form)."','".x($_POST['month'])."')";
}
mysql_query("insert into `subject` values ".implode(",",$rows));

删除所有变量分配,并确保在某处定义$form - 我在您发布的代码中没有看到它。

// $post = a sanitized copy of $_POST

$entries = array( );
for ($i = 1; $i <= 6; ++$i) {
    $entries[] = " (NULL, '{$post['sub'.$i]}', '{$post['Ts'.$i]}', '{$post['Attend_s'.$i]}', '{$form}', '{$post['month']}') ";
}

$query = " INSERT INTO `subject` VALUES ".implode(', ', $entries);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM