Reputation: 1099
I need your help to solve a silly problem. I have 2 tables in my database (contents and categories).
I have populated my MySQL table called "categories", and now I want to see in a form the old category stored in the database while I modify it to a new one.
Unfortunately what I wrote shows only the list of the categories get from the database table.
<select name="PostedCat">
<?php
$query_category = "SELECT * FROM categ";
$result_category = mysql_query($query_categ) or die (mysql_error());
while($categ = mysql_fetch_assoc($result_category)){
?>
<option value="<?php echo $categ['cat_title']; ?>" ><?php echo $categ['cat_title']; ?></option>
<?php
}
?>
</select>
With this code I can see the categories stored in the database, but how can I get the "old" selected one? The stored one?
Hope in some help, but I'm blind at the moment.
Thank you in advance.
Upvotes: 1
Views: 3411
Reputation: 1099
So, thank you again for the kindness. Here is what I did.
I have a page with the list of all my contents and near each one of those I have and "Edit" button. When I click it, I go to a new page with a filled form that takes data directly from MySQL and place quite everything in the correct field. In the function.php I have:
function getPost($id) {
$id = (int) $id;
$query = mysql_query("SELECT * FROM contents WHERE id = '$id'") or die (mysql_error());
return mysql_fetch_array($query);
}
In the edit.php I have this for example:
<?php $editedpost = getPost($_GET['id']); ?>
<form action="editingPost.php" method="post">
<table>
<tr>
<td><label for="ContentTitle">Title</label></td>
<td><input type="text" name="ContentTitle" value="<?php echo $editedpost['content_title']; ?>" /></td>
</tr>
<tr>
<td><label for="ContentCategory">Category</label></td>
<td>
<select name="ContentCategory">
<?php
$query_category = "SELECT * FROM categ";
$result_category = mysql_query($query_categ) or die (mysql_error());
while($categ = mysql_fetch_assoc($result_category)){
?>
<option value="<?php echo $categ['cat_title']; ?>" >Here I would like to see the data stored in the database, that I choosed before.</option>
<?php
}
?>
</select>
</td>
</tr>
<tr>
<td colspan="2"><input type="submit" name="submit_post_new" /></td>
<td><input type="hidden" name="id" value="<?php echo $_GET['id']; ?>" /></td>
</tr>
</table>
</form>
Upvotes: 0
Reputation: 65342
Assuming your old category is in $oldcat
, just do
$query_category = "SELECT * FROM categ";
$result_category = mysql_query($query_categ) or die (mysql_error());
while($categ = mysql_fetch_assoc($result_category)){
?>
<option value="<?php echo $categ['cat_title']; if ($categ['cat_title']==$oldcat) echo '" selected="true'; ?>" ><?php echo $categ['cat_title']; ?></option>
<?php
}
?>
Upvotes: 2