【问题标题】:inserting multiple values against multiple ids in database table在数据库表中针对多个 id 插入多个值
【发布时间】:2015-11-21 10:20:34
【问题描述】:

我有一个表单,它同时获取所有员工的 datetime intime out,并将其提交到名为出席。员工的姓名是从数据库表中获取的,每个员工都有一个唯一的 ID。 现在的问题是,我如何格式化可以一次将数据插入数据库的查询。这是我的 php 代码。

<?php 
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "employee_record";

// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$output="";
    $query= "SELECT * ";
    $query.= "FROM employe ";
    $result=mysqli_query($conn,$query);
        if(!$result){
            echo ("Database query failed. ".mysqli_connect_error());
        }
    <form  action="test.php" method="POST" >
        <table border="1" style="margin-top: 20px">
            <thead>
                <th>Employee Name</th>
                <th>Date</th>
                <th>Time In</th>
                <th>Time Out</th>
            </thead>
            <tbody>
        <?php   
        $id=array();
        $date=array();
        $timein=array();
        $timeout=array();
        while($employe = mysqli_fetch_assoc($result)){ 
                echo "<tr><td>";
                    echo "<input type=\"hidden\" name=\"id[]\" value=\"";
                     echo $employe['id']; 
                    echo "\"/>";
                     echo $employe['firstname']." ".$employe['lastname']."</td>";
                     echo "<td><input type=\"date\" name=\"date[]\" value=\"\"/></td>";
                     echo "<td><input type=\"datetime-local\" name=\"timein[]\" value=\"\"/></td>";
                     echo "<td><input type=\"datetime-local\" name=\"timeout[]\" value=\"\"/></td>";
                echo "</tr>";
        }
    ?>
    </tbody>
    </table>
    <input type="submit" name="submit" value="Submit" />
    </form>
?>

现在说我有这样的数据.. 编号(1,2,3), 日期(日期 1,日期 2,日期 3), 时间(时间1,时间2,时间3), 超时(时间1,时间2,时间3)。 数据量会有所不同,因为 m 从数据表中获取 id,其中员工人数可能或多或少。现在我只是坚持如何将这些数据插入到数据库中的 id 中。 任何帮助将不胜感激..

【问题讨论】:

  • 似乎所有日期都一样?!?但不管怎样,这类事情都有教程
  • 一个表单可能有多少行。我问是因为一次插入一行代码很简单。如果您使用准备好的查询和事务,它将相当快。只需要大约行数 - 数十、数百、数千条记录?

标签: php mysql


【解决方案1】:

更新(2019 年)

在查看了我原来的答案后,我意识到我今天不会使用那种方法。基本上是因为现在我知道,在单个事务中逐行执行一个准备好的语句已经足够快了,除非我们谈论的是数千行(当数据是用户生成时不太可能出现这种情况)。答案中还缺少任何 SQL 注入保护,现在参数化查询没有问题。

$ids      = [];
$dates    = [];
$timeIns  = [];
$timeOuts = [];

// validate $_POST data and put into arrays above

$stmt = $conn->prepare("
    UPDATE attendance SET
        date    = ?,
        tiemeIn = ?,
        timeOut = ?
    WHERE user_id = ?
");

$numRows = count($ids);

$conn->begin_transaction();
    for ($i = 0; $i < $numRows; $i++) {
        $stmt->bind_param('sssi', $date[$i], $timeIns[$i], $timeOuts, $ids[$i]);
        $stmt->execute();
    }
$conn->commit();

原始答案(2015 年)

要插入包含 N 列的多 (M) 行,您可以使用以下语法:

INSERT INTO tablename 
    (colname1, colname2, .. , colnameN) 
VALUES
    (valueRow1Colname1, valueRow1Colname2, .. , valueRow1ColnameN),
    (valueRow2Colname1, valueRow2Colname2, .. , valueRow2ColnameN),
    ..
    (valueRowMColname1, valueRowMColname2, .. , valueRowMColnameN);

您可以使用函数 joinimplode 使用 PHP 创建该查询。

$ids      = array();
$dates    = array(); 
$timeIns  = array();
$timeOuts = array();

// validate $_POST data and put into arrays above

$numInserts = count($ids);
if ($numInserts > 0) {
    $values = array();
    for ($i = 0; $i < $numInserts; $i++) {
        $values[] = "({$ids[$i]}, '{$dates[$i]}', '{$timeIns[$i]}', '{$timeOuts[$i]}')";
    }
    $valuesJoined = join(',', $values);

    $query = "
        INSERT INTO attendance (user_id, date, tiemeIn, timeOut)
        VALUES {$valuesJoined}
        ON DUPLICATE KEY UPDATE 
            date    = VALUES(date),
            tiemeIn = VALUES(tiemeIn),
            timeOut = VALUES(timeOut)
    ";
    $result=mysqli_query($conn,$query);
}

【讨论】:

  • 我似乎很有帮助,但我想做一些类似 {“INSERT INTO 出勤(日期,tiemeIn,超时)值 {$valuesJoined} WHERE user_id={multiple ids..}”}。那么查询会是什么??
  • 它不会像你写的那样工作。你可以写INSERT ... WHERE user_id IN (1, 5, 6),但是你会为每个用户插入相同的值。但如果user_id 是唯一键或主键,您可以将ON DUPLICATE KEY UPDATE 用于已有条目的用户。
【解决方案2】:

如果我正确理解了这个问题,那么也许这些方面的内容可能会有所帮助。当然,这未经您的数据测试,但我认为这个想法应该可行。

/*
    ------------------------------
    To process the form submission
    ------------------------------
*/

$update=false;/* change this if the final output sql looks correct..*/
$keys=array_keys( $_POST );
$length=count( $_POST[ $keys[ 0 ] ] );

for( $i=0; $i < $length; $i++ ){

    $params=array();

    foreach( $keys as $field ) {
        $value=$_POST[ $field ][ $i ];

        if( $field!=='id' ) $params[]="`{$field}`=\"".str_replace('"',"'",$value)."\"";
        else $where=" where `id`='".$value."';";
    }

    $sql="update `employee` set ".implode(', ',$params ) . $where;
    if( $update ) $result=mysqli_query( $conn, $sql );
    else echo $sql.'<br />';
}

【讨论】:

  • 让它在您的方法中进行一些更改。谢谢:)
【解决方案3】:
if(isset($_POST['submit']) ){

    print_r($_POST);// die;
                /*        Array
                (
                    [date] =2019-11-18
                    [id] = Array
                        (
                            [8] = 8
                            [9] = 9
                            [11] = 11
                            [14] = 14
                            [15] = 15
                            [17] = 17
                            [16] = 16
                        )

                    [a_status] = Array
                        (
                            [8] = present
                            [9] = present
                            [11] = present
                            [14] = present
                            [15] = present
                            [17] = present
                            [16] = present
                        )

                    [submit] = Submit
                )*/

    $i=0;
      $id =$_POST['id'];
      $a_status = $_POST['a_status'];
      $date = $_POST['date'];

      foreach ($a_status as $key => $id) {

        $sql = "INSERT INTO `tbl_attendance`(`stid`, `date`, `a_status`) VALUES('$key','".$_POST['date']."','$id')";
        echo $sql; //die;
        $res = mysqli_query($conn,$sql);
        // print_r($res);
        $i++;
      }
    //hi
}

?>

【讨论】:

  • 你能补充更多解释吗?
猜你喜欢
  • 1970-01-01
  • 2015-07-02
  • 2018-09-27
  • 2020-06-22
  • 1970-01-01
  • 2017-04-27
  • 1970-01-01
  • 2014-06-08
  • 1970-01-01
相关资源
最近更新 更多