使用一个查询MySQL插入多行

时间:2012-09-19 20:03:15

标签: php mysql

我想编写脚本,带有多个插入查询的函数。 让我更好地解释一下。

我以html格式输入一个quantity。 我有MySQL查询将registered user插入表中。 所以我希望我的函数为“数量”次插入此查询。

 mysql_query("INSERT INTO `pxlot` (realname,email,address,phone,status,regtime,ip) 
 VALUES ('$realname','$email','$address','$phone','0','$dateTime','$ip')")
 or die (mysql_error()); // Inserts the user.

例如插入3次。 有什么建议?

8 个答案:

答案 0 :(得分:90)

 INSERT INTO table (a,b) VALUES (1,2), (2,3), (3,4);

http://dev.mysql.com/doc/refman/5.5/en/insert.html

答案 1 :(得分:19)

以下是一些方法

INSERT INTO pxlot (realname,email,address,phone,status,regtime,ip) 
select '$realname','$email','$address','$phone','0','$dateTime','$ip' 
from SOMETABLEWITHTONSOFROWS LIMIT 3;

INSERT INTO pxlot (realname,email,address,phone,status,regtime,ip) 
select '$realname','$email','$address','$phone','0','$dateTime','$ip'
union all select '$realname','$email','$address','$phone','0','$dateTime','$ip'
union all select '$realname','$email','$address','$phone','0','$dateTime','$ip'

INSERT INTO pxlot (realname,email,address,phone,status,regtime,ip) 
values ('$realname','$email','$address','$phone','0','$dateTime','$ip')
,('$realname','$email','$address','$phone','0','$dateTime','$ip')
,('$realname','$email','$address','$phone','0','$dateTime','$ip')

答案 2 :(得分:17)

在大多数情况下,使用一个Insert语句插入多个记录在MySQL中要比在PHP中插入带有for / foreach循环的记录快得多。

我们假设$ column1和$ column2是由html表单发布的具有相同大小的数组。

您可以像这样创建查询:

<?php
    $query = 'INSERT INTO TABLE (`column1`, `column2`) VALUES ';
    $query_parts = array();
    for($x=0; $x<count($column1); $x++){
        $query_parts[] = "('" . $column1[$x] . "', '" . $column2[$x] . "')";
    }
    echo $query .= implode(',', $query_parts);
?>

如果为两条记录发布数据,查询将变为:

  

INSERT INTO TABLE(column1column2)VALUES('data','data'),('data','data')

答案 3 :(得分:1)

虽然使用单个 INSERT 语句插入多行通常更快,但它会导致更复杂且通常不安全的代码。下面我将介绍使用 PHP 一次性插入多条记录的最佳实践。

要同时向数据库中插入多行新行,需要遵循以下3个步骤:

  1. 启动事务(禁用自动提交模式)
  2. 准备INSERT声明
  3. 多次执行

使用数据库事务可确保将数据保存在一块并显着提高性能。

如何使用 PDO 正确插入多行

PDO 是 PHP 中最常见的数据库扩展选择,使用 PDO 插入多条记录非常简单。

$pdo = new \PDO("mysql:host=localhost;dbname=test;charset=utf8mb4", 'user', 'password', [
    \PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION,
    \PDO::ATTR_EMULATE_PREPARES => false
]);

// Start transaction
$pdo->beginTransaction();

// Prepare statement
$stmt = $pdo->prepare('INSERT 
    INTO `pxlot` (realname,email,address,phone,status,regtime,ip) 
    VALUES (?,?,?,?,?,?,?)');

// Perform execute() inside a loop
// Sample data coming from a fictitious data set, but the data can come from anywhere
foreach ($dataSet as $data) {
    // All seven parameters are passed into the execute() in a form of an array
    $stmt->execute([$data['name'], $data['email'], $data['address'], getPhoneNo($data['name']), '0', $data['regtime'], $data['ip']]);
}

// Commit the data into the database
$pdo->commit();

如何使用mysqli正确插入多行

mysqli 扩展使用起来有点麻烦,但操作原理非常相似。函数名不同,参数略有不同。

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new \mysqli('localhost', 'user', 'password', 'database');
$mysqli->set_charset('utf8mb4');

// Start transaction
$mysqli->begin_transaction();

// Prepare statement
$stmt = $mysqli->prepare('INSERT 
    INTO `pxlot` (realname,email,address,phone,status,regtime,ip) 
    VALUES (?,?,?,?,?,?,?)');

// Perform execute() inside a loop
// Sample data coming from a fictitious data set, but the data can come from anywhere
foreach ($dataSet as $data) {
    // mysqli doesn't accept bind in execute yet, so we have to bind the data first
    // The first argument is a list of letters denoting types of parameters. It's best to use 's' for all unless you need a specific type
    // bind_param doesn't accept an array so we need to unpack it first using '...'
    $stmt->bind_param('sssssss', ...[$data['name'], $data['email'], $data['address'], getPhoneNo($data['name']), '0', $data['regtime'], $data['ip']]);
    $stmt->execute();
}

// Commit the data into the database
$mysqli->commit();

性能

这两个扩展都提供了使用事务的能力。使用事务执行准备好的语句大大提高了性能,但仍然不如单个 SQL 查询。然而,差异是如此的微不足道,为了简洁和干净的代码,多次执行准备好的语句是完全可以接受的。如果您需要一个更快的选项来一次将多条记录插入到数据库中,那么很可能 PHP 不是正确的工具。

答案 4 :(得分:0)

如果您想要插入多个值,请从具有不同帖子值但插入相同表格的多个输入中说明,然后只需使用:

mysql_query("INSERT INTO `table` (a,b,c,d,e,f,g) VALUES 
('$a','$b','$c','$d','$e','$f','$g'),
('$a','$b','$c','$d','$e','$f','$g'),
('$a','$b','$c','$d','$e','$f','$g')")
or die (mysql_error()); // Inserts 3 times in 3 different rows

答案 5 :(得分:0)

使用以下功能在单个查询中插入多行

function multiple_insert($table, $fields = array(), $values = array(), $appendix = false, $ret = false) {

$query = 'INSERT INTO';
$query .= ' `' . $this->escape($table) . "`";

if (is_array($fields)) {
    $query .= ' (';
    $num = 0;
    foreach ($fields as $key => $value) {
        $query .= ' `' . $value . '`';
        $num++;
        if ($num != count($fields)) {
            $query .= ',';
        }
    }
    $query .= ' ) VALUES ';

    foreach ($values as $key => $value) {
        $query .= '(';
        foreach ($value as $key => $value) {
            $query .= "'" . $value . "'" . ',';
        }
        $query = rtrim($query, ',');
        $query .= '),';
    }

    $query = rtrim($query, ',');

    if ($appendix) {
        $query .= ' ' . $appendix;
    }
    if ($ret) {
        return $query;
    }

    $this->sql    = $query;
    $this->result = mysqli_query($this->mysql, $query);
    if (mysqli_error($this->mysql) != '') {
        $this->_error(mysqli_error($this->mysql));
        $this->result = null;
        return false;
    } else {
        return $this;
    }

}

}

这就是您将如何使用该功能

 $values_array = array(
         ['videoid1' , 'chneneid1' , 'descitpin1'] ,
         ['videoid2' , 'chneneid3' , 'descitpin3'] 

     );

     $table_columns = array('video_id' , 'channelId' , 'description');

     multiple_insert($table_name , $table_columns , $values_array );

答案 6 :(得分:-1)

<?php   
$datas = ['1','2','3'];
$datas = ['1','2','3'];
foreach ($datas as $key => $data) {     
    $query_value[] = "('" . $data . "', '" . $datas[$key] . "')";       
}
echo $value_string = implode(",", $query_value);
?>

答案 7 :(得分:-3)

在这里,我使用forech进行多行插入。.我的代码在php和mysqli中。 我的第一页是Add_timetable.php,它的视图类似于此图像。Preview of Add_timetable.php 结果预览就是这样。.Result Preview

此页面命名为Add_timetable1.php     

foreach($_POST['days'] as $row=>$Days)
{include 'dbcon.php';
$s=mysqli_real_escape_string($conn,($_POST['cl']));
$n=mysqli_real_escape_string($conn,($_POST['di']));
$g=mysqli_real_escape_string($conn,($_POST['days'][$row]));
//echo $g[$i];
$a=mysqli_real_escape_string($conn,($_POST['p1'][$row]));
$b=mysqli_real_escape_string($conn,($_POST['p2'][$row]));
$c=mysqli_real_escape_string($conn,($_POST['p3'][$row]));
$d=mysqli_real_escape_string($conn,($_POST['p4'][$row]));
$e=mysqli_real_escape_string($conn,($_POST['p5'][$row]));

$ins=mysqli_query($conn,"select Timetable_Id from key_table");
while ($row=mysqli_fetch_assoc($ins))
                             {


          $att=$row['Timetable_Id']+1;      
          $_SESSION['pp']=$att;   

  }
 $ttid=$_SESSION['pp'];
 $ins1=mysqli_multi_query($conn,"insert into 
 tbl_timetable(T_Id,Class,Division,Days,period1,period2,period3,period4,period5) 
 values('$ttid','$s', '$n', '$g','$a','$b','$c','$d','$e')");

 $upd=mysqli_query($conn,"update Key_table set Timetable_Id ='$ttid'");
 //$ins2=mysqli_query($conn,"insert into tbl_login values('$u','$pas','Staff')");
 }
 ?>
   <script>
   alert("Timetable added successfully");
   window.location="Add_Timetable.php";
   </script>
   You can try this code i am it works correctly..