简体   繁体   English

php:mysql_insert_id()问题

[英]php: mysql_insert_id() issues

Can the php function mysql_insert_id() return no result after processing the INSERT query in mysql db? 在mysql db中处理INSERT查询后,php函数mysql_insert_id()是否可以返回结果?

Just to clarify. 只是为了澄清。 There was a script performing by cron on the production site. cron在生产网站上执行了一个脚本。 It contained a cycle for generating invoices for users. 它包含一个为用户生成发票的周期。 Each iteration consists of a INSERT db query and the mysql_insert_id() operation going right after the query - to fetch the generated invoice number. 每次迭代都包含一个INSERT数据库查询和在查询后立即执行的mysql_insert_id()操作 - 以获取生成的发票号。 A set of iterations were performed without fetching the last inserted number. 执行一组迭代而不获取最后插入的数字。

Can it be caused by high db server load or by some other reasons that are not linked to the problem at the php code site? 它可能是由高数据库服务器负载引起的,还是由于与PHP代码站点上的问题没有关联的其他原因引起的?

Any help would be appreciated! 任何帮助,将不胜感激!

Offhand, I can think of a few cases where MySQL wouldn't return the ID: 另外,我可以想到一些MySQL不会返回ID的情况:

  • The table you're inserting into doesn't have an AUTO_INCREMENT ed primary key. 您要插入的表没有AUTO_INCREMENT ed主键。
  • You're inserting multiple rows at once. 您正在一次插入多行。
  • You're calling mysql_insert_id() from a different connection than the INSERT query was executed. 您从与执行INSERT查询不同的连接调用mysql_insert_id()
  • The INSERT query didn't succeed (for instance, it encountered a deadlock). INSERT查询未成功(例如,它遇到死锁)。 Make sure you are checking the return value from mysql_query() , then use mysql_errno() and mysql_error() . 确保从mysql_query()检查返回值,然后使用mysql_errno()mysql_error()

MySQL docs have a full list of conditions and details on how this function works . MySQL文档有完整的条件列表和有关此函数如何工作的详细信息

Of course, it's also possible there is a bug in MySQL, which would depend on which version of MySQL you are using. 当然,MySQL中也可能存在一个错误,这取决于您使用的是哪个版本的MySQL。

If you're running the commands through a shell script, and run them both separately as in; 如果您通过shell脚本运行命令,并单独运行它们,如同;


mysql -e "insert into table ( field1 ) values ( 'val1' );" "database"

lastId=`mysql -e "select last_insert_id();" "database"`

Then that won't work as the second call makes a new connection to the server. 然后,当第二个调用与服务器建立新连接时,这将不起作用。 You need to do something like the following, as it is all done within a single database call / connection; 您需要执行以下操作,因为它们都是在单个数据库调用/连接中完成的;


lastId=`mysql -e "
                  insert into table ( field1 ) values ( 'val1' );
                  select last_insert_id();
                 " "database"`

You'll need to look up the extra parameters required for the MySQL command to remove formatting and header row - I'm afraid I can't remember them off the top of my head! 你需要查找MySQL命令所需的额外参数来删除格式和标题行 - 我担心我无法忘记它们!

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

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