美好的一天,
我愿意检索 Mysql 中新插入的行的 id 值。
我知道有 mysqli_insert_id 函数,但是:
我不想冒险去查询最高的id,因为有很多查询,它可能会给我错误的......
(我的id列是自动递增的)
https://github.com/mysqljs/mysql#getting-the-id-of-an-inserted-row 很好地描述了解决方案:
connection.query('INSERT INTO posts SET ?', {title: 'test'}, function(err, result, fields) {
if (err) throw err;
console.log(result.insertId);
});
var table_data = {title: 'test'};
connection_db.query('INSERT INTO tablename SET ?', table_data , function(err, result, fields) {
if (err) {
// handle error
}else{
// Your row is inserted you can view
console.log(result.insertId);
}
});
您也可以访问此链接查看https://github.com/mysqljs/mysql#getting-the-id-of-an-inserted-row
const 查询 = '插入礼品卡(卡号、卡余额、卡到期日期、收件人电子邮件、商店 ID、客户 ID)值 (?,?,?,?,?,?)';
常量值 = [卡号、卡余额、卡到期日期、收件人电子邮件、商店 ID、客户 ID];
const [results] = await db.execute(query, values);
const lastInsertId = results.insertId;
console.log('Last Inserted ID:', lastInsertId);
我认为您误解了
mysqli_insert_id()
方法的使用。该方法必须在插入语句之后立即执行,以获得最后插入的id。如果你直接用我的 MySQL 来完成
INSERT INTO(a,b)values(1,'test');
SELECT LAST_INSERT_ID(); -- this will display the last inserted id