MySQL:通过PHP基于逗号分隔值在数据库中插入多行

时间:2014-07-28 13:59:38

标签: php mysql

我有一个名为document_bank的表,我曾经为每条记录生成ref no。

我的表格字段如下

id,ref_no,subject,student

我曾经使用以下查询生成ref_no

$result17 = "Select document_bank.id As id
From document_bank
Order By document_bank.id Desc
Limit 1 ";
$row197 = mysql_query($result17);
while($row17 = mysql_fetch_array($row197))
{
if($row17['id'])
{
$ref=$row17['id'];
}
}
$refn= $ref+1;

{ref_no}="Lotus/".date('Y')."/".$refn."";

{Subject}="test msg";
{student}="120131, 120134, 120153";

i used this query insert single record

$insert99= "INSERT INTO `document_bank`( `ref_no`, `subject`, `student`) VALUES ({ref_no},{subject},{student})";
mysql_query($insert99);

我希望我的查询根据{student}的3个值插入3行。每行必须只有一个学生,每行也应增加ref_no

2 个答案:

答案 0 :(得分:0)

为了根据学生插入多行,您可以将值分解为数组。

$student="120131, 120134, 120153";

//Remove spaces and split into array.
$student_array = explode(",",str_replace(' ','',$student)); 

for($i=0;$i < count($student_array);$i++) {

  $result17 = "Select document_bank.id As id
    From document_bank
    Order By document_bank.id Desc
    Limit 1 ";
  $row197 = mysql_query($result17);
  while($row17 = mysql_fetch_array($row197)) {
    if($row17['id']) {
      $ref=$row17['id'];
    }
  }
  $refn= $ref+1;

  {ref_no}="Lotus/".date('Y')."/".$refn."";

  {Subject}="test msg";

  $insert99= "INSERT INTO `document_bank`( `ref_no`, `subject`, `student`) VALUES ({ref_no},{subject},". $student_array[$i] . ")";
}

explode() PHP Reference

答案 1 :(得分:0)

您可以使用此代码插入多行。

$query = "Select document_bank.id As id
        From document_bank
        Order By document_bank.id Desc
        Limit 1 ";
$result = mysql_query($query);
$result_set = mysql_fetch_array($result);

$refn = 1;
if (!empty($result_set['id']))
    $refn = $result_set['id'] + 1;

$ref_no = "Lotus/" . date('Y') . "/" . $refn;

$Subject = "test msg";
$student = "120131, 120134, 120153";

$records = implode(',', $student);

foreach($records as $value){

    $ref_no = "Lotus/" . date('Y') . "/" . mysql_insert_id() + 1;
    $value = trim($value);
    $insert = "INSERT INTO `document_bank`( `ref_no`, `subject`, `student`) VALUES ('$ref_no', '$subject', '$value')";
    mysql_query($insert);
}