dongliangkeng1056 2019-03-15 07: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 07: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条)
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部