在数据库表中为多个ID插入多个值

时间:2015-11-21 10:20:34

标签: php mysql

我的表单会立即将所有员工的日期时间超时提交到名为的数据库表中考勤。从数据库表中获取员工的姓名,每个员工都有唯一的ID。  here is my form table 现在的问题是,我如何格式化可以立即将数据插入数据库的查询。这是我的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>
?>

现在说我有像......的数据 ID(1,2,3), 日期(DATE1,DATE2,DATE3), timeIn(TIME1,TIME2,时间3), 超时(TIME1,TIME2,时间3)。  数据量的变化因为从数据表中获取ID,其中员工数量可以更多或更少。现在我只是坚持如何将数据插入数据库中的ID。 任何帮助将不胜感激..

3 个答案:

答案 0 :(得分:2)

更新(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);

您可以使用函数 join implode 使用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);
}

答案 1 :(得分:0)

如果我正确地理解了这个问题,那么沿着这些方向的某些东西可能有所帮助当然,这是未经测试的数据,但我认为这个想法应该有效。

/*
    ------------------------------
    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 />';
}

答案 2 :(得分:-1)

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
}

?>
相关问题