简体   繁体   English

从表单中获取数据的 SQL 更新查询未运行

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

I have a form set up on a users profile, so if they want to update items such as their first name, last name, username, or email then they can.我在用户个人资料上设置了一个表单,因此如果他们想要更新诸如他们的名字、姓氏、用户名或电子邮件之类的项目,那么他们可以。

When they hit the submit on the form, a PHP script runs which essentially checks if any fields are not empty, and if there are not empty, run an update query to the db on the student table.当他们点击表单上的提交时,会运行一个 PHP 脚本,它基本上检查是否有任何字段不为空,如果不为空,则对student表上的数据库运行更新查询。 However, nothing seems to be happening, wondering if someone could point out where I have gone wrong as the student table does not update?但是,似乎什么也没发生,想知道是否有人可以指出我哪里出错了,因为student表没有更新?

profile.php:配置文件.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>

Edit Details编辑详情

PHP: 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");
}

?>

STUDENT TABLE学生桌学生表

1: 1:

You are wide open for SQL injection here.您在这里对 SQL 注入持开放态度。 Use Parameterised Queries.使用参数化查询。 ALWAYS.总是。

2: 2:

Check Your PHP Error logs检查您的PHP 错误日志

3: 3:

D on't d on't
R epeat [R EPEAT
Y ourself自己

Which means use PHP loop structures to save code and time and effort.这意味着使用PHP 循环结构来节省代码和时间和精力。

4: 4:

Be aware that MySQL UTF-8 is NOT really UTF-8 and should always be replaced by utf8mb4_ character sets and collations.要知道,MySQL的UTF-8是不是真的UTF-8 ,应始终被替换utf8mb4_字符集和归类。

5: 5:

Your header Location redirects should always be followed by an exit / die() statement because PHP will keep processing until it reaches the end of the script, even if you give it a header .你的header位置重定向应该总是跟在exit / die()语句之后,因为 PHP 会一直处理直到到达脚本的末尾,即使你给它一个header If you give multiple header "Location: ..." s then the final one is the one that will be followed.如果您提供多个标题"Location: ..."则最后一个是将遵循的标题。

6: 6:

PHP has lots of array implosion and string interaction functions for you to use arrays in the context of turning them into Parameterised queries. PHP 有许多数组内爆和字符串交互函数,您可以在将它们转换为参数化查询的上下文中使用数组。

7: 7:

Use Try / Catch blocks in PHP These should be used to catch errors and issues before they're committed. 在 PHP 中使用Try / Catch 块这些应该用于在提交之前catch错误和问题。

8: 8:

NEVER ever trust user input.永远不要相信用户输入。 Ever.曾经。


Quick and Dirty Example:快速而肮脏的例子:

Using MySQLi ?使用 MySQLi ? syntax;句法;

In your db.php file, to allow try/catch error catching with the MySQLi method:在您的 db.php 文件中,允许使用 MySQLi 方法捕获 try/catch 错误:

    \mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

In your script....在你的脚本中......

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