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 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 spring后端vue前端
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题