mysql在insert之后获取列值?

laximzn5  于 2021-06-18  发布在  Mysql
关注(0)|答案(2)|浏览(386)

在这段代码中,在向db.i插入值之后,我正在执行select查询来选择invoiceno($sql1=“select invoiceno from invoices order by invoiceid desc limit 1”;)。而不是从数据库中选择如何获取invoiceno?
例如:假设有两个用户。两个用户同时插入invoiceid。在执行“select invoiceno from invoices order by invoiceid desc limit 1”时;这将获取最后一个发票ID。我需要获取特定的发票ID(针对特定用户)。如何获取它?

$query          = "select * from invoices order by invoiceID desc limit 1";
$result         = $link->query($query);
$row            = $result->fetch_assoc();
$invoiceNo      = $row["invoiceNo"];
$getinvoiceNo   = str_pad($invoiceNo + 1, 4, 0, STR_PAD_LEFT); //inserting like 0000
$sql            = "INSERT INTO invoices (invoiceNo)
                   VALUES ('$getinvoiceNo')";
if ($link->query($sql) === TRUE) {
   //echo "1";
   $sql1    = "select invoiceNo from invoices order by invoiceID desc limit 1";
   $last_id = mysqli_insert_id($link, $sql1);
   $result1 = mysqli_query($link, $sql1);
   $row1    = mysqli_fetch_array($result1);
   echo json_encode($row1);
} else {
    echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
mysql_close($link);
rekjcdws

rekjcdws1#

如果您希望防止发票号码发生冲突,则只需将表创建为

CREATE TABLE invoices (
     invoiceID INTEGER NOT NULL AUTO_INCREMENT,
     other columns . . .
     PRIMARY KEY (invoiceID)
);

当你插入时,不要插入invoiceid,让mysql来做。
这将确保每个新发票都有一个唯一的invoiceid。

m2xkgtsf

m2xkgtsf2#

如果我对您的问题理解正确,您会担心并发更新记录可能导致的数据损坏。
我想你应该看看。。。对于更新语法,它应该执行您要求的操作:锁定所选行,直到触发更新。然后锁就会松开。
例如:

SELECT table_field FROM table_name WHERE table_id_field = id_param FOR UPDATE

将锁定选定行,直到

UPDATE table_name SET table_field = table_field + 1 WHERE table_id_field = id_param

相关问题