用php在sql数据库中插入多行

时间:2015-12-27 06:55:25

标签: php mysql sql

在检查几个条件后,我想用php在sql中插入多行。

条件是,如果'cat'和'preview'不为null,则第一行将被提交,如果'cat','preview','cat2','preview2'不为null,则提交两行第一行的值'cat'和'preview和第二行的值'cat2'和'preview2'。

我尝试了这些代码,但是我看到了 - 未定义的变量:sql

我的情况怎么了?

else if(isset($cat)and ($cat!=="") and isset($preview)and ($preview=="") and 
(isset($cat2))and ($cat2!=="") and (isset($preview2))and ($preview2!==""))
  { 
   $sql = "INSERT INTO files (cat, preview, file, art) VALUES 
         ('".$cat."','".$preview."','".$file."','".$art."')
         ('".$cat2."','".$preview2."','".$file2."','".$art2."')";
  }

3 个答案:

答案 0 :(得分:0)

您的代码只有查询错误,您只想在一个插入命令中插入两行。使用此代码分隔插入命令:

else if(!empty($cat) and !empty($preview) and
!empty($cat2) and !empty($preview2))
{  
$sql = "INSERT INTO files (cat, preview, file, art) VALUES 
                      ('".$cat."','".$preview."','".$file."','".$art."');";
$sql .= " INSERT INTO files (cat, preview, file, art) VALUES ('".$cat2."','".$preview2."','".$file2."','".$art2."');";
}

答案 1 :(得分:0)

使用;插入查询不是一个查询...

例如

Insert into mytable (a,b,c) values (1,2,3); 
Insert into mytable (a,b,c) values (4,5,6); 
Insert into mytable (a,b,c) values (7,8,9);

不是一个查询,这是3个插入查询。

这意味着当插入值(4,5,6)出错时,值(1,2,3)查询成功....

我们希望如果一行失败,则所有插入查询都会失败。

因此,我们不会使用;

编写插入查询

示例查询:

Insert into mytable values(1, 2, 3), (4, 5, 6), (7, 8, 9);

答案 2 :(得分:0)

我个人认为你的条件逻辑可能需要重新思考。例如,如果将值保存到数组中,则可以自动执行此过程:

// Save first values
$sqlArgs[]  =   array($cat,$preview,$file,$art);
// Save second values
$sqlArgs[]  =   array($cat2,$preview2,$file2,$art2);
// Loop through each row.
foreach($sqlArgs as $key => $array) {
    // If the `cat` or the `preview` empty, skip
    if(!empty(trim($array[0])) && !empty(trim($array[1])))
        $sql[]  =   "'".implode("','",$array)."'";
}
// If the sql has rows continue
if(!empty($sql)) {
    // Build the statement rows with implode() of values.
    // This assumes these are not user-input values or that you have
    // thoroughly sanitized the values.
    $statement  =   "INSERT INTO `files` (`cat`,`preview`,`file`,`art`) VALUES (".implode("),(",$sql).")";
    // Preview statement 
    print_r($statement);
}

这种方法将根据两个键cat&来处理0,1或2个插入(如果需要,可以更多)。 preview被填满。