簡體   English   中英

插入新記錄並更新MySQL表記錄。-PHP

[英]Insert new record and Update MySQL table records .- PHP

我有一個MySQL表。

|id|page  |page_number
|1 |name1 |3
|2 |name2 |2
|3 |name3 |1
|4 |name2 |4

用戶可以添加新頁面,但是要添加到當前頁面之后。 例如,當前頁面為1(頁面編號),那么新頁面(頁面編號)必須為2,然后必須更新1之后的所有其他頁面,頁面編號+1並插入頁面編號為2的新頁面。 還是可能首先我必須插入新頁然后更新所有頁碼?

這里的標准解決方案是什么,是否有標准解決方案?

我用這樣的foreach嘗試過:

$count = 1;
// loop over all pages 
foreach($pages->fetchAll() as $page){
    // if count is less than new-page order then continue add 1 to       
    // counter
    if($new_page_order > $count){
       $count++;
       continue;
    }

    // get unique id for current page
    $current_id = $page['id'];
    $new_order= $count+1;

    // update current page with page_order+1
    $query = $conn->prepare("UPDATE pages SET    
             page_order='".$new_order."' WHERE id=".$current_id);
    $query->execute();
    //add +1 to count, because it is used for page_order value
    $count++;
}
// add new page
$query = $conn->prepare("INSERT INTO pages (columns... page_order)     
VALUES( values , ..., $new_page_order)");

我怎樣才能做到這一點 ?

由於您只需要更新插入的頁碼之后的頁碼,因此可以運行如下查詢:

"UPDATE pages SET page_number = page_number + 1 WHERE page_number >= ".$current_id

在插入之前

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM