我有一张名为&#34的订单;订单"在SQL数据库中:
if ( !empty($_POST)) {
$name = $_POST['name'];
$valid = true;
if ($valid) {
$pdo = Database::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO orders (name,date) values(?,CURDATE())";
$q = $pdo->prepare($sql);
$q->execute(array($name));
Database::disconnect();
}
}
" id"设置为AUTO_INCREMENT和"日期"当我通过我的PHP表单插入数据时创建:
id date name orderID
========================
1 1502 John 15021
2 1502 Jane 15022
我希望" orderID"的价值是从值" id"自动创建的。和"日期":
<!-- ionic/angularjs js -->
<script src="lib/ionic/js/ionic.bundle.js"></script>
<script src="js/ng-cordova.min.js"></script>
<script src="js/ng-cordova-mocks.min.js"></script>
<script src="js/barcodescanner.js"></script>
<!-- cordova script (this will be a 404 during development) -->
<script src="cordova.js"></script>
<!-- your app's js -->
<script src="js/app.js"></script>
<script src="js/controllers.js"></script>
答案 0 :(得分:0)
由于事实,id是AUTO_INCREMENT
,您无法接受此值。但它很简单。向表中添加AFTER INSERT
触发器,然后让它更新orderID
列。
这是AFTER UPDATE
触发器的快速示例。
CREATE TRIGGER yourTrigger
AFTER INSERT
ON yourTable FOR EACH ROW
BEGIN
UPDATE yourTable
SET orderid = CAST(date as char(4)) + CAST(id as char(1))
WHERE ID = NEW.id
END;
答案 1 :(得分:0)
试
if ($valid) {
$pdo = Database::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO orders (name,date) values(?,CURDATE())";
$q = $pdo->prepare($sql);
$q->execute(array($name));
$q = $pdo->prepare( '
update orders
set orderId = id
where id = SELECT LAST_INSERT_ID()'
);
$q->execute();
Database::disconnect();
}
现在应该工作
答案 2 :(得分:0)
SET @last_id_in_table1 = LAST_INSERT_ID();
INSERT INTO orders (name,date,orderID) values(?,CURDATE(),@last_id_in_table1 )
答案 3 :(得分:0)
不要在数据库中创建另一个列来保存此值,它只是重复的数据,只会占用不必要的空间。
检索数据时,可以使用CONCAT(id, date) AS orderid
来获取连接值。
例如,获取John的所有orderid:
SELECT CONCAT(id,date) AS orderid from `orders` WHERE `name`="John"