Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 697161
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 14, 20262026-05-14T03:08:23+00:00 2026-05-14T03:08:23+00:00

I want to item’s subcatory selected when editing category: <?php function categoryFormEdit() { $ID

  • 0

I want to item’s subcatory selected when editing category:

<?php
  function categoryFormEdit()
 {
  $ID = $_GET['id'];
  $query = "SELECT * FROM category WHERE id= $ID";
  $result = mysql_query($query);
  $row = mysql_fetch_array($result);
  $subcat = $row['subcat'];
  $text = '<div class="form">
        <h2>Add new category</h2>
          <form method="post" action="?page=editCategory">
              <ul>
                  <li><label>Kategori</label></li>
                  <li><input type="text" class="inp" name="cname" value="' . $row['name'] . '"></li>
                  <li><label> Aç&#305;klama</label></li>
                  <li><textarea class="inx" rows="10" cols="40" name="kabst">' . $row['description'] . '</textarea></li>
                  <li>
                    <select class="ins" name="kselect">
                      <option value="1">Aktif</option>
                      <option value="0">Pasif</option>
                    </select>
                  </li>
                  <li>Üst kategorisi</li>
                  <li>
                    <select class="ins" name="subsl">';
                        $s = "SELECT * FROM category";
                        $q = mysql_query($s);
                        while ($r = mysql_fetch_assoc($q)) {
                            $text .= '<option value="' . $r['id'] . '" ' . sQuery() . '>' . $r['name'] . '</option>';
                        }
                    $text .= '</select>
                 </li>

                     <li>Home page:</li> 
                     <li>
                       <input type="radio" value="1" name="kradio"> Active
                       <input type="radio" value="0" name="kradio"> YPassive
                     </li>
                     <li><input type="submit" class="int" value="ekle" name="ksubmit"></li>
                </ul>
            </form>
        </div>';
  return $text;
 }

 function sQuery()
 {
    if ($r['id'] == $subcat) {
      $t = "selected";
    } 
    else {

      $t = "";
    }
   return $t;
  }
?>

With above code there is not selected item. What is wrong in my script?
Thanks in advance

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-14T03:08:23+00:00Added an answer on May 14, 2026 at 3:08 am

    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:

    <?php error_reporting(-1); // turn on all errors
    
    function getCategoryFormEdit($id)
    {
      $categories = getCategories();
      $category   = getCategoryFromRowsById($categories, $id);   
      $selectBox  = createCategorySelectBoxOptions($categories, $category['subcat']);
    
      $html = getRenderedTemplate('categoryFormEdit.tpl.html', array(
          '{{category:name}}',
          '{{category:description}}',
          '{{category:selectBoxOptions}}',  
      ), array(
          $category['name'],
          $category['description'],
          $selectBox
      ));
    
      return $html;
    }
    

    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(
                '<option value="%s"%s>%s</option>',
                $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:

    <div class="form">
        <h2>Add new category</h2>
        <form method="post" action="?page=editCategory">
            <ul>
                <li><label>Kategori</label></li>
                <li><input type="text" class="inp" name="cname" 
                           value="{{category:name}}"></li>
                <li><label> Aç&#305;klama</label></li>
                <li><textarea class="inx" rows="10" cols="40" name="kabst">{{category:description}}</textarea></li>
                <li>
                    <input type="checkbox" class="ins" name="kselect" id="kselect">
                    <label for="kselect">Aktif/Pasif</label>
                </li>
                <li>Üst kategorisi</li>
                <li>
                    <select class="ins" name="subsl">
                        {{category:selectBoxOptions}}
                    </select>
                </li>
                <li>Home page:</li> 
                <li>
                    <input type="checkbox" class="ins" name="kradio" id="kradio">
                    <label for="kradio">Aktif/Pasif</label>
                </li>
                <li><input type="submit" class="int" value="ekle" name="ksubmit"></li>
            </ul>
        </form>
    </div>
    

    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.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a custom QGraphicsView and a custom QGraphicsItem. I want the Item to
I want to append .item element before .content element but it just simply removes
I'm deleting an item and want to pop-up a confirmation window before doing all
I've got several list items, when I click on the item I want the
I want to search two item (name=string and location=json). this search is (one input
** I want one single list item to have fistname, last name and the
I want to create an item to sitecore using code behind. I found this
I want add new Feed item on entity persist and update. I write this
i want the item name (in the page title) to post back to facebook...
I have list of object that I want each item to be rendered with

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.