首页 > 解决方案 > Optimised PHP code for multiple input check

问题描述

There is a PHP update form where a user can update his records. The below-mentioned code looks redundant to me. How can I optimize this PHP code? Also, I have the admins username and email in a different table and the admin detail columns (such as first name, last name, gender, dob) in a different table. What will be the best way to check if username and email both have been updated or if any one of them and update it in the database accordingly.

Below is my source code:

   if(isset($_POST['btnClick']) {
    $f_name = NULL;
    $l_name = NULL;
    $username = NULL;
    $email = NULL;
    $gender = NULL;
    $dob = NULL;

    $f_name = filter_input(INPUT_POST, "f_name", FILTER_SANITIZE_STRING);
    $l_name = filter_input(INPUT_POST, "l_name", FILTER_SANITIZE_STRING);
    $username = filter_input(INPUT_POST, "username", FILTER_SANITIZE_STRING);
    $email = filter_input(INPUT_POST, "email", FILTER_VALIDATE_EMAIL);
    $gender = filter_input(INPUT_POST, "gender", FILTER_VALIDATE_STRING);
    $dob = filter_input(INPUT_POST, "dob", FILTER_VALIDATE_STRING);

    try {

        if(isset($username) && $username != $_SESSION['username']) {
            $sqlUpdate = "UPDATE admins SET username=:username WHERE admin_id=:admin_id";
            /*Update code here...*/
            echo "Username changed value inputted";
        }  
        else if(isset($email) && $email != $_SESSION['email']) {
            $sqlUpdate = "UPDATE admins SET username=:username WHERE admin_id=:admin_id";
            /*Update code here...*/
            echo "email change value inputted";
        } 
        else if(isset($username) && isset($email)) {
            /*Update both records */
        }

标签: php

解决方案


你可以这样做:

<?php
try {
    if (isset($username) && $username != $_SESSION['username']) {
        $fieldsToUpdate[] = 'username=:username';
        $updatedFields[] = 'Username';
    }

    if (isset($email) && $email != $_SESSION['email']) {
        $fieldsToUpdate[] = 'email=:email';
        $updatedFields[] = 'Email';
    }

    if (isset($fieldsToUpdate) && count($fieldsToUpdate) > 0) {
        $sqlUpdate = "UPDATE admins SET " . implode($fieldsToUpdate, ', ') . " WHERE admin_id=:admin_id";
        /*Update code here...*/
        $finalMessage = 'Fields: ' . implode($updatedFields, ', ') . ' have been updated.';
    }
}

PS:这是一个示例代码,如何使用 PHP 数组和 implode() 函数优化代码以运行单个查询来更新单个或多个字段。


推荐阅读