MySQL-为什么LAST_INSERT_ID()对我不起作用? [英] MySQL- Why is LAST_INSERT_ID() not working for me?

查看:275
本文介绍了MySQL-为什么LAST_INSERT_ID()对我不起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

  public function createNewGuide($userID,$guideName)
  {
    $sql =" INSERT INTO myTable(name, updated) 
            VALUES ('$guideName', 'NOW()')";

    //Process query
    $this->query($sql); // This inserts the new row
    $this->query('LAST_INSERT_ID()'); // This throws an error

    return $this->query_result;
  }

我的查询功能如下:

  private function query($sql) 
  {
      $this->query_result = mysql_query($sql, $this->conn)
        or die("Unable to query local database <b>". mysql_error()."</b><br>$sql");   
  } 

我收到以下错误:

MySQL数据库错误:您的SQL语法有错误;检查 对应于您的MySQL的手册 正确语法的服务器版本 在"LAST_INSERT_ID()"附近使用

MySQL Database Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'LAST_INSERT_ID()'

我已经搜索了类似的问题,但没有找到答案:(

I've googled and looked at similar problems, but not found an answer :(

我还没有尝试过 PHP函数mysql_insert_id(),因为我真的很想使用SQL来做到这一点.

I have not tried the PHP function mysql_insert_id(), as I really would like to do this using SQL.

推荐答案

为什么不只使用PHP的

Why not just use PHP's mysql_insert_id?

无关紧要...

SELECT LAST_INSERT_ID()

...只要表中有一个自动递增的列,就应该起作用.

...should work as long as you've an auto-increment column in the table.

这篇关于MySQL-为什么LAST_INSERT_ID()对我不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆