简体   繁体   English

如何在最后一个数据库条目中插入一个值?

[英]How can I insert a value into the last database entry?

I have a little tricky code, maybe you have a better solution:我有一个有点棘手的代码,也许你有更好的解决方案:

What I want to do is, take the "id" of the last inserted entry from the database (1), then put two zeros infront of it (001), take the current "date" and format it (1506) and insert all together (1506001) again into the same row in my database into "orderID".我想要做的是,从数据库(1)中取出最后一个插入条目的“id”,然后在它前面放两个零(001),取出当前的“日期”并对其进行格式化(1506)并插入所有一起(1506001)再次进入我数据库中的同一行中的“orderID”。

        $pdo = Database::connect();
        $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

        $sql1 = 'SELECT * FROM orders ORDER BY `date` DESC LIMIT 1';
        foreach ($pdo->query($sql1) as $row) {

          $dateID = date("ym", strtotime($row['date'])); 
          $id = sprintf("%03d", $row['id']);
          $orderID = $dateID.$id;

          $sql2 = "INSERT INTO orders (orderID) values('$orderID') ";
          $q2 = $pdo->prepare($sql2);
          $q2->execute();

          Database::disconnect();
        }

For example:例如:

id  date   name    orderID
==========================
1   1505   John    1505001
2   1505   Jane    1505002
1   1506   Mad     1506001
2   1506   Fred    1506002

What happens now is, that a new row is created.现在发生的是,创建了一个新行。 The value of "oderID" is not stored into the same row and I do not know how to achieve this. “oderID”的值未存储在同一行中,我不知道如何实现。

You need to use UPDATE instead of INSERT :您需要使用UPDATE而不是INSERT

    $sql2 = "UPDATE `orders` SET `orderID` = '$orderID' 
    WHERE 
        `id` = {$row['id']} 
    AND `date` ='{$row['date']}'
    AND `name` = '{$row['name']}' 
    AND `orderID` ='{$row['orderID']}'
    AND `orderID` != '$orderID'";

I assume after the first INSERT the field orderID is NULL.我假设在第一次 INSERT 后,字段 orderID 为 NULL。
You could therefore run a query that updates ALL records WHERE orderID IS NULL .因此,您可以运行更新所有记录WHERE orderID IS NULL的查询。 No need to pull any values into PHP, MySQL's lpad(), date_format() and concat functions should do the trick.无需将任何值拉入 PHP,MySQL 的 lpad()、date_format() 和 concat 函数应该可以解决问题。

sscce : sscce :

<?php
$pdo = new PDO('mysql:host=localhost;dbname=test;charset=utf8', 'localonly', 'localonly', array(
    PDO::MYSQL_ATTR_DIRECT_QUERY => false,
    PDO::ATTR_ERRMODE=>PDO::ERRMODE_EXCEPTION
));
setup($pdo);

/* insert new orders */
$stmt = $pdo->prepare('INSERT INTO soFoo (`name`, `date`) VALUES (:name, Now())');
$stmt->bindParam('name', $name);
foreach( array('John', 'Jane', 'Matt', 'Fred') as $name ) {
    $stmt->execute();
}

/* 'fix' orderIDs */
$pdo->exec("
    UPDATE
        soFoo
    SET
        orderID = concat(
            date_format(`date`, '%y%m'),
            lpad(`id`, 3, '0')
        )
    WHERE
        orderID IS NULL
");


/* print result */
foreach( $pdo->query('SELECT * FROM soFoo', PDO::FETCH_ASSOC) as $r ) {
    echo join(', ', $r), "\r\n";
}


function setup($pdo) {
    $pdo->exec('
        CREATE TEMPORARY TABLE soFoo (
            `id` int auto_increment,
            `date` Date,
            `name` varchar(32),
            `orderID` varchar(32),
            primary key(id)
        )'
    );
}

prints (today):印刷品(今天):

1, 2015-06-19, John, 1506001
2, 2015-06-19, Jane, 1506002
3, 2015-06-19, Matt, 1506003
4, 2015-06-19, Fred, 1506004

...but that still leaves the question what you will do once there are a thousand orders in that table. ...但这仍然留下了一个问题,一旦该表中有一千个订单,您将做什么。

All you need to do is:您需要做的就是:

  1. Use mysql_insert_id() to get last inserted id使用mysql_insert_id()获取最后插入的 id
  2. Create your new value for field orderID为字段 orderID 创建新值
  3. Update your table for id you have got through mysql_insert_id()更新您通过mysql_insert_id()获得的 id 表

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM