简体   繁体   English

PHP MySQLi 准备好的语句事务插入 ID

[英]PHP MySQLi Prepared Statement Transaction Insert ID

So I'm looking into create a MySQLi Transaction with prepared statements in PHP.所以我正在研究用 PHP 中的准备好的语句创建一个 MySQLi 事务。 I seem to have the idea all fine, however I have an issue.我的想法似乎很好,但是我有一个问题。 My statements rely on each other.我的陈述相互依赖。 For example:例如:

Email address entered into email table.电子邮件地址输入电子邮件表。 User entered into user table with Email Address ID as a foreign key用户以电子邮件地址 ID 作为外键进入用户表

See code below, which shows two prepared statements, the second relying on the first for the e-mail ID:请参阅下面的代码,其中显示了两个准备好的语句,第二个依赖于第一个作为电子邮件 ID:

//$email_sql
                if(!($stmt = $mysqli->prepare($email_sql))) throw new \Exception("[mysqli] Prepare failed: (" . $mysqli->errno . ") " . $mysqli->error);
                if(!($stmt->bind_param('s', $email)) throw new \Exception("[mysqli] Bind Params failed: (" . $mysqli->errno . ") " . $mysqli->error);
                //$user_sql
                if(!($stmt = $mysqli->prepare($user_sql))) throw new \Exception("[mysqli] Prepare failed: (" . $mysqli->errno . ") " . $mysqli->error);
                if(!($stmt->bind_param('i', $SHOULD_BE_EMAIL_ID)) throw new \Exception("[mysqli] Bind Params failed: (" . $mysqli->errno . ") " . $mysqli->error);

You can see where I have put '$SHOULD_BE_EMAIL_ID', there is where the issue lies.你可以看到我把“$SHOULD_BE_EMAIL_ID”放在哪里,问题就在这里。 As I can see, there's no way for me to get this value as the first query hasn't yet been executed at this point in the code.正如我所见,我无法获取此值,因为此时代码中的第一个查询尚未执行。 Is there a way for me to get round this?我有办法绕过这个吗? Ie is there any functions that will allow me to get the email ID there.即是否有任何功能可以让我在那里获取电子邮件 ID。 As far as I can see, I have not been able to find one.据我所知,我还没有找到一个。

The only way I can think of a solution at the moment, is changing the logic of my code, so it does utilise transactions, which if I can avoid, I will.目前我能想到解决方案的唯一方法是更改​​我的代码逻辑,因此它确实利用了事务,如果我可以避免,我会这样做。

Many thanks for any help.非常感谢您的帮助。

These two statements这两种说法

I'm looking into create a MySQLi Transaction (1)我正在考虑创建一个 MySQLi 事务 (1)
I will avoid transactions if I can (2)如果可以,我会避免交易(2)

Looks mutual exclusive to me.对我来说看起来相互排斥。

So, your answer is very simple and can be based on two logical conclusions:因此,您的答案非常简单,可以基于两个合乎逻辑的结论:

  • you cannot have a transaction without having a transaction没有交易就不能有交易
  • besides, you cannot execute a query without executing a query.此外,您不能在不执行查询的情况下执行查询。

So, just start using transactions if you need them.所以,如果你需要它们,就开始使用它们。

That's all.就这样。

For Fetching the last inserted ID using PDO::lastInsertId().用于使用 PDO::lastInsertId() 获取最后插入的 ID。 And separate the insertion into two statements [made 1st statement insert and another updation].并将插入分成两个语句[使第一个语句插入和另一个更新]。

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

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