dongliangkeng1056 2019-03-15 15:29
浏览 26
已采纳

mySQL中的php自动递增ID与存储的不同[关闭]

So on my web page i have a database connection setup. Once a user posts a comment on the web page it adds the comment to the database and a column in the database called ID gets incremented by 1. This ID serves as the primary key for the each row in the database. So when the user wants to remove a comment it checks the database for the comment that has matching primary key.

My current solution is this.

add the comment to the database

the database adds the ID

get the ID from the database

store it together with the comment in an array

When a user clicks delete comment check if the comment ID matches the ID in the database.

My problem with this is that it feels weird calling the database to add the comment and then call the database again to get the comment ID.

Is there any better solution to this?

  • 写回答

2条回答 默认 最新

  • dryb38654 2019-03-15 15:38
    关注

    Below I've added some code based on your question. Let's say you've a table called comments where you're inserting some values and as the id is an auto incremented field so it is inserted automatically with your passed data. So if you try with php and mysql then after your insert operation you can easily get the last inserted id without doing another extra query for inserted id using $conn->insert_id

    $sql = "INSERT INTO comments(commenter, comment)
    VALUES ('John', 'How are you?')";
    
    if ($conn->query($sql) === TRUE) {
        $last_id = $conn->insert_id;
        echo "New record created successfully. Last inserted ID is: " . $last_id;
    } else {
        echo "Error: " . $sql . "<br>" . $conn->error;
    }
    

    REF.: http://php.net/manual/en/mysqli.insert-id.php

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?