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çı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
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
getCategoryFormEditdoes 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:
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:
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:Notice how I have not included ID directly into the query but with
sprintfand%d. In your code, you used$ID = $_GET['id']and then inserted$IDdirectly 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
getCategoryFormEditagain, you will notice that we are not callinggetCategoryById($id)though, but the following function: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:
Again, all this function does is one thing: it creates select options. Nothing more. It also adds the
selectedattribute to the option that has$row['id']identical to the specified$selectedId. Usingsprintfagain 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 justselectedwhen 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:
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:
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_replaceto replace all placeholders with their corresponding values and return the filled-in template to whatever function called it, e.g.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:
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.