簡體   English   中英

這個數據庫查詢怎么了?

[英]what's wrong with this database query?

這是PHP中的一小段代碼。

<?php include_once("includes/connection.php"); ?>
    <?php include_once("includes/functions.php"); ?>
    <?php 
        if(!isset($_POST['menu_name']) or !isset($_POST['position']) or !isset($_POST['visible'])){
            echo "You are supposed to fill all entries<br/><br/><a href='new_subject.php'>go back</a>";
            exit;
        }
            echo "<pre>";
            var_dump($_POST); 
            echo "</pre>":
        $menu_name = $_POST['menu_name'];
        $position = (int)$_POST['position'];
        $visible = $_POST['visible'];
        $menu_name = mysql_real_escape_string($menu_name);
        $subject_count = mysql_num_rows(get_all_subjects());
        //$subject_set_desc = mysql_query("SELECT position FROM subjects ORDER by position DESC",$connection);
        for($change = $position;$change<=$subject_count;$change++){
            //get row with position $change
            //increase it's position by 1
            //continue till all rows end OR loop ends
            /*UPDATE subjects SET position = $change+1 WHERE position = $change*/
            $new_position = $change+1;
            echo "{$change} ".gettype($change)."  {$new_position} ".gettype($new_position)."<br/> ";
            mysql_query("UPDATE subjects SET position = {$new_position} WHERE position = {$change}",$connection);
            echo "UPDATE subjects SET position = {$new_position} WHERE position = {$change}"."<br/>";
            //confirm_query($cheack);

        }
        $query = "INSERT INTO subjects (menu_name,position,visible) VALUES ('{$menu_name}',{$position},{$visible})";
        if(mysql_query($query,$connection)){
            //header("location:content.php");
            exit;
        } else{
            echo "<b>failed to insert new subject</b> <br/>".mysql_error();
        }
    ?>
    <?php mysql_close($connection); ?>

我希望您只關注for循環和該循環中的數據庫查詢。.我通過post將以下數據發送到此頁面

$_POST['subject'] = 'new_subject'; //string type <br/>
$_POST['position'] = 1 //int type <br/>
$_POST['visible'] = 1 //tinyint type <br/>
$_POST['submit'] = 'Add Subject' // string type just submisssion <br/>

如您在我的表單處理文件中看到的

在此處輸入圖片說明

這些查詢之前我的數據庫

在此處輸入圖片說明

查詢后我的數據庫(在代碼循環中)。

在此處輸入圖片說明

我認為表中所有行的位置應增加1,但所有行都更改為5。在這里,我想為位置大於或等於$_POST['position']..<br/>的行將位置增加1 $_POST['position']..<br/>我試着回顯我的查詢,所有查詢都表明查詢是正確的,但是在執行完表后,我卻無法進行更改(我想將每個位置加1)。

您應該向下運行; 首先將位置1更新為2。 現在有2個項目的位置為2。然后將其更新為三個。 在職位3上剩下三個項目。

而是從最大值開始,將4更新為5。然后將其刪除,然后將所有3遞增為4,以此類推。

甚至更好的是,對所有需要遞增的位置使用一個查詢,而不會發生任何循環:

Update subjects SET position = position +1
$new_position = $change+1;

將該行更改為:

$new_position = $position+1;

並將其放在for循環之前。

出問題的是您一次更改了每個值。

UPDATE subjects SET position = position + 1 WHERE position >= ...

暫無
暫無

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

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