drfals1307 2015-06-15 19:47
浏览 57

获取最后插入的ID并将其用作PHP / MySQL的参数

I'm very new to PHP, trying to figure things out.

I have the following php code:

$read_more = '<a href="http://www.example.com/index.php?id=' . mysqli_insert_id($conn)  . '" target="_self">[read more]</a>';

$sql = "INSERT INTO database (date, headline, article, read_more) VALUES ('$_POST[date]', '$_POST[headline]', '$_POST[article]', '$read_more')";

The code is returning "http://www.example.com/index.php?id=0". Note that the "id" parameter is returning "0". My goal is to make it return the latest ID from the database, which is set to auto increment.

I've tried many things but nothing worked for me so far. Thanks!

EDIT: After hours of trial and error, this is how I was able to solve this problem:

//After connecting to the database

$sql = "INSERT INTO table (date, headline, article, read_more) VALUES ('$_POST[date]', '$_POST[headline]', '$_POST[article]', '$read_more')";
$result = mysqli_query($conn, $sql);
$id = mysqli_insert_id($conn);

Now the latest id is saved into a variable that I can use.

  • 写回答

1条回答 默认 最新

  • douzhi4830 2015-06-16 00:58
    关注

    Try something like this instead. Check the documentation here.

    // insert a datarow, primary key is auto_increment
    // value is a unique key
    $query = "INSERT INTO test (value) VALUES ('test')";
    mysql_query( $query );
    
    echo 'LAST_INSERT_ID: ',
          mysql_query( "SELECT LAST_INSERT_ID()" ),
          '<br>mysql_insert_id: ',
          mysql_insert_id();
    
    评论

报告相同问题?

悬赏问题

  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?