php - 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".
$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.
Answer
Solution:
I assume after the first INSERT the field orderID is NULL.
You could therefore run a query that updates ALL records
WHERE orderID IS NULL
. No need to pull any values into PHP, MySQL's lpad(), date_format() and concat functions should do the trick.sscce:
prints (today):
...but that still leaves the question what you will do once there are a thousand orders in that table.
Answer
Solution:
You need to use
UPDATE
instead ofINSERT
:Answer
Solution:
All you need to do is: