duancifu6769 2016-08-13 02:59
浏览 123
已采纳

为什么UPDATE会创建新记录?

For event listing page. After inserting record into db I capture last ID with

//Store ID[LAST]
    $ID = mysqli_insert_id($db);

Next the page shows event formatted for easy reading. Then user can hold or approve item for publication with 2 buttons: Draft, Publish. I use submits buttons for each:

//Check ID value (use for testing)
    echo "<p>ID = ".$ID."</p>
";

    echo "<form action='".$_SERVER['PHP_SELF']."' method='GET'>
    <input type='submit' name='submitDraft' value='Draft' />
    <input type='submit' name='submitPublish' value='Publish' />
    </form>";

Now I use conditional to update record according to button chosen. (Note connect.php is include that manages passcodes and connection statement.)

if (isset($_REQUEST["submitDraft"])) {
    include('includes/connect.php');
    $sql="UPDATE sessions SET postit='0' WHERE ID='$ID'";
    if (mysqli_query($db, $sql)) {
            echo "Record updated successfully";
        } else {
            echo "Error updating record: " . mysqli_error($db);
        }

        mysqli_close($db);
    }

    if (isset($_REQUEST["submitPublish"])) {
    include('includes/connect.php');
    $sql="UPDATE sessions SET postit='1' WHERE ID='$ID'";
    if (mysqli_query($db, $sql)) {
            echo "Record updated successfully";
        } else {
            echo "Error updating record: " . mysqli_error($db);
        }

        mysqli_close($db);
    }

My problem is UPDATE statement adds new record to table but should update same record. What is my mistake please.

  • 写回答

2条回答 默认 最新

  • douwen3500 2016-08-13 20:37
    关注

    I solve this. Because form resubmit whole page, insert statement is run each time and add new record. This record also get update so appear like UPDATE is add new record. Really INSERT make new record and UPDATE change 'postit' field in same time. To fix I add conditional if $_REQUEST not equal submitDraft or submitPublish then INSERT, else it skip over INSERT. Also I just see same kind of answer from @Jay Patel and @SBA. Thank you to both

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

报告相同问题?

悬赏问题

  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘