开发者

Problem with selected subcategory when editing Category items

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开发者_Go百科><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


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.


I have solved the problem by:

$selected = $d == $subcat ? " selected " : "";
$text .= '<option value="'.$d.'" '.$selected.' >'.$r['name'].'</option>';

function sQuery($x, $y) {

 $selected = $x == $y ? " selected " : "";
 return $selected;                                   
}


You need to use the global keyword inside the function:

 function sQuery()
 {
    global $r['id'];
    global $subcat;

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

      $t = "";
    }
   return $t;
  }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜