Problem with selected subcategory when editing Category items

后端 未结 3 1068
萌比男神i
萌比男神i 2021-01-28 04:54

I want to item\'s subcatory selected when editing category:



        
3条回答
  •  走了就别回头了
    2021-01-28 05:42

    Ok, last time I tried to help you, you went on a downvote rampage on me (which the SO team kindly reversed btw), so I don't know why I am helping you this time, but here is some improvements to your code, including the desired feature.

    Basically, your code is a messy and hard to read mixture of HTML and PHP that does way too much in one function. If something goes wrong, you don't know where. We will break it down into smaller reusable chunks. That will increase maintainability, readability and security.

    Here is what the code will look like in the end:

    As you can see, I have broken down the code and now it is easy to understand what it does from the function names. Basically, all getCategoryFormEdit does now, is getting everything it needs to assemble the HTML for you. The remaining stuff is done in other functions. This makes the code much easier to handle, because now it only does one thing, instead of four. It is considered good practice to keep functions small and let them do one thing at a time, because if something goes wrong, you don't have to go searching over a couple hundred lines of code, but only in your small function.

    The other functions are as follows:

    function queryDatabase($sql)
    {
        $result = mysql_query($sql);
        $rows   = mysql_fetch_array($result);
        return $rows;    
    }
    

    Because you will do the querying and the fetching multiple times, we refactor the code to call the database into a separate function. We are lazy and don't want to reproduce these calls in our code time and time again. Instead we just pass this function some SQL and have it return the rows from the query, with the queries being:

    function getCategories()
    {
        return queryDatabase('SELECT id, name, description, subcat FROM category');
    }
    

    You had the query with * in your version. It is considered good practice to only fetch from the database what you really need from it, which is why I have replaced it with the column names found in the HTML. Database queries are expensive and the less you query the database, the better. Second one:

    function getCategoryById($id)
    {
        $sql = sprintf(
            'SELECT name, description, subcat 
            FROM category WHERE id = %d', $id);
    
        return queryDatabase($sql);
    }
    

    Notice how I have not included ID directly into the query but with sprintf and %d. In your code, you used $ID = $_GET['id'] and then inserted $ID directly into the SQL String, opening your code for SQL Injection. Never ever do that. You cannot trust user input and should always sanitize it. With %d, we make sure ID is a number and only a number.

    If you look at getCategoryFormEdit again, you will notice that we are not calling getCategoryById($id) though, but the following function:

    function getCategoryFromRowsById($rows, $id)
    {
        foreach($rows as $row) {
            if($row['id'] === $id) {
                return $row;
            }
        }
        return FALSE;
    }
    

    The reason for this is simple: when doing getCategories() you have already fetched all categories from the database, so there is no reason to requery the database again to get just one specific category, because it is included in the rows returned in all categories. Remember db queries are expensive, so let's just iterate over all categories and pick the row with the given $id from there instead.

    Once you got all categories you can use them to create the select options:

    function createCategorySelectBoxOptions($rows, $selectedId)
    {
        $options = '';
        foreach($rows as $row) {
            $options .= sprintf(
                '',
                $rows['id'],
                ($rows['id'] === $selectedId) ? ' selected="selected"' : '',
                $rows['name']
            );
        }
        return $options;
    }
    

    Again, all this function does is one thing: it creates select options. Nothing more. It also adds the selected attribute to the option that has $row['id'] identical to the specified $selectedId. Using sprintf again instead of string concatenation, because it is much easier to read and adds less clutter to your code. Also note that I used XHTML notation for the selected attribute. You can do just selected when using an HTML flavor.

    Finally, all the stuff we just prepared has to get into the template. For this, you just create template file and add some code with placeholders to it:

    Add new category

    • Üst kategorisi
    • Home page:

    The reason why we use a template instead of writing all the HTML into the function is because we want to separate presentation and logic. You might be working with a designer who knows no PHP, but can do HTML and this way, you can divide work easily. It's also easy to just change the template without having to search in your PHP code where you put it.

    Next we need a way to replace placeholders, which is what the following method is for:

    function getRenderedTemplate($template, $placeholder, $replacements)
    {
       return str_replace($placeholder, $replacements, file_get_contents($template));
    }
    

    This is an extremely simplied approach to templating. You could also use DOM for templating or a dedicated template engine like Twig or something else. For this example, I just wanted to have it simple, so I used str_replace to replace all placeholders with their corresponding values and return the filled-in template to whatever function called it, e.g.

    if(is_numeric($_GET['id'])) {
        echo getCategoryFormEdit($_GET['id']);
    } else {
        die('Category ID must be numeric. Exiting');
    }
    

    And that's it. Refactoring done. I didn't test the above code, so there is likely some bugs in it, but anyway: the main point was to illustrate how to improve code like shown in the question. Basically, whenever your functions get very long look try to describe the code in words. For every "and" refactor the code into a smaller portion that just does one thing. By doing so to the above, we have gained:

    • a reusable query function that returns rows from SQL
    • a reusable function that gets all categories from the DB
    • a reusable function that gets a category by ID
    • a reusable function that creates a select box from categories
    • a reusable mini template engine
    • separation of presentation and business logic
    • fixed obvious SQL Injection vulnerability
    • better readability and maintainability.

    If you come back to the code in a few weeks or months, you will have a much less hard time to figure out what it does.

提交回复
热议问题