簡體   English   中英

從表單中獲取數據的 SQL 更新查詢未運行

[英]SQL Update Query taking data from a form isn't running

我在用戶個人資料上設置了一個表單,因此如果他們想要更新諸如他們的名字、姓氏、用戶名或電子郵件之類的項目,那么他們可以。

當他們點擊表單上的提交時,會運行一個 PHP 腳本,它基本上檢查是否有任何字段不為空,如果不為空,則對student表上的數據庫運行更新查詢。 但是,似乎什么也沒發生,想知道是否有人可以指出我哪里出錯了,因為student表沒有更新?

配置文件.php:

<form action="scripts/update-profile.php" method="post">  
    <h3 class="left-align fontAmaticH1">Student Details</h3>
        <p class="left-align"><b>Username: </b><?php echo $row['username']; ?>
        <div class="update-profile"><input type="text" name="username" placeholder="Update Username..."></div>    
        </p>

        <p class="left-align"><b>Email Address: </b><?php echo $row['email']; ?>
        <div class="update-profile"><input type="text" name="email" placeholder="Update Email..."></div>
        </p>

        <p class="left-align"><b>First Name: </b><?php echo $row['firstName']; ?>
        <div class="update-profile"><input type="text" name="firstName" placeholder="Update First Name..."></div>
        </p>

        <p class="left-align"><b>Surname: </b><?php echo $row['lastName']; ?>
        <button name="update-details" class="update-details" type="submit">Update Details</button>
        </form>

編輯詳情

PHP:

<?php
// Checking whether the user got to this page by clicking the proper button.
if (isset($_POST['update-details'])) {

      require 'db.php';

// We grab all the data which we passed from the update form
    $studentID = $_SESSION['studentID'];

    $username = $_POST['username'];
    $email = $_POST['email'];
    $profileImage = $_POST['profileImage'];
    $firstName = $_POST['firstName'];
    $lastName = $_POST['lastName'];


    $update = [];
    if (! empty($username)) {
        $update['username'] = "username ='".$username ."'";
    }

    if (! empty($email)) {
        $update['email'] = "email='".$email ."'";
    }

    if (! empty($firstName)) {
        $update['firstName'] = "firstName='".$firstName ."'";
    }

    if (! empty($lastName)) {
        $update['lastName'] = "lastName='".$lastName ."'";
    }


    if (! empty($update)) {
        $query = "UPDATE `student` SET ";
        $query .= implode(', ', $update);
        $query .= " WHERE `student`.`studentID` = $studentID ";
        $result = $conn->query($query) or die ("update SQL error");
    }


    header("Location: ../profile.php?update=success");
}

?>

學生桌學生表

1:

您在這里對 SQL 注入持開放態度。 使用參數化查詢。 總是。

2:

檢查您的PHP 錯誤日志

3:

d on't
[R EPEAT
自己

這意味着使用PHP 循環結構來節省代碼和時間和精力。

4:

要知道,MySQL的UTF-8是不是真的UTF-8 ,應始終被替換utf8mb4_字符集和歸類。

5:

你的header位置重定向應該總是跟在exit / die()語句之后,因為 PHP 會一直處理直到到達腳本的末尾,即使你給它一個header 如果您提供多個標題"Location: ..."則最后一個是將遵循的標題。

6:

PHP 有許多數組內爆和字符串交互函數,您可以在將它們轉換為參數化查詢的上下文中使用數組。

7:

在 PHP 中使用Try / Catch 塊這些應該用於在提交之前catch錯誤和問題。

8:

永遠不要相信用戶輸入。 曾經。


快速而骯臟的例子:

使用 MySQLi ? 句法;

在您的 db.php 文件中,允許使用 MySQLi 方法捕獲 try/catch 錯誤:

    \mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

在你的腳本中......

if (isset($_POST['update-details'])) { //tacky but it will do.

      require 'db.php';

    $studentID = (int)$_SESSION['studentID']; 
                  // force to type integer to ensure 
                  // data is always valid.

    unset($_POST['update-details']); // forget this value. 
    $update = []; // make a new array
    // Because your array keys are the same, you can simply loop through 
    // checking and then adding from one array to another. 
    // 
    // alternatively you can copy the whole @_POST array and simply 
    // run `array_filter` on it to clean it of empty values. 
    // (but this will not catch whitespaces)
    foreach($_POST as $key=>$data){
          $data = trim($data);
          if(!empty($data)){
             // use REGEX to do some cleaning of your Key values. 
             // NEVER EVER trust user input. NEVER. 
             $key = preg_replace("/[^a-z]/i","",$key);
             $update[$key] = $data;
          }
    }
    // end foreach. 
    if (\count($update) > 0 ) {
        $keyString = implode(" = ? ,",array_keys($update));
        $keyString." = ?" //append last reference

        // Now build the dynamically built Parameterised SQL:
        $query = "UPDATE `student` SET ".$keyString." WHERE `student`.`studentID` = ? ";
        
        $runQuery = $conn->prepare($query);

        // We will assume here all your data is a string (s) type. 

        $dataType = str_repeat("s", count($update));
        $dataType .= "i"; // append data type for the ID at the end. 
        $update[] = $studentID;
        

        //Use a Try / Catch block to check the functions work correctly. 
        // you can also use SQL transactions. 
        try {
            // Bind your data to your query object
            $runQuery->bind_param($dataType, \implode(",",$update));
            // Execute your query.
            $runQuery->execute(); 
            $runQuery->free_result();
           
            // This can feedback the number of rows updated. 
            $rows = (string)$runQuery->affected_rows;
            error_log("Rows updated: ".$rows);
           
            //close your query. 
            $runQuery->close();
        }
        catch(\mysqli_sql_exception $ex) {
             // Do something with your query failure. 
             error_log("MySQL Error!: ".print_r($ex,true));
         } 
    } //end count update

    header("Location: ../profile.php?update=success");
    exit; // STOP further PHP execution. 
}

暫無
暫無

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

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