douyan8266 2016-09-13 11:27
浏览 62

PHP MySQLi准备语句事务插入ID

So I'm looking into create a MySQLi Transaction with prepared statements in PHP. 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

See code below, which shows two prepared statements, the second relying on the first for the e-mail 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. 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? I.e. is there any functions that will allow me to get the email ID there. 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.

  • 写回答

2条回答 默认 最新

  • doushi1957 2016-09-13 11:43
    关注

    These two statements

    I'm looking into create a MySQLi Transaction (1)
    I will avoid transactions if I can (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.

    评论

报告相同问题?

悬赏问题

  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用