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 高价求中通快递查询接口
  • ¥15 解决一个加好友限制问题 或者有好的方案
  • ¥15 关于#java#的问题,请各位专家解答!
  • ¥15 急matlab编程仿真二阶震荡系统
  • ¥20 TEC-9的数据通路实验
  • ¥15 ue5 .3之前好好的现在只要是激活关卡就会崩溃
  • ¥50 MATLAB实现圆柱体容器内球形颗粒堆积
  • ¥15 python如何将动态的多个子列表,拼接后进行集合的交集
  • ¥20 vitis-ai量化基于pytorch框架下的yolov5模型
  • ¥15 如何实现H5在QQ平台上的二次分享卡片效果?