So you have both category
and a catid
column in your posts
table? You should normalize your table. Only have catid
in your posts
table and reference it in a categories
table.
If you don't normalize, later on, what if you decide to rename your category Car
to Sedan
. Then you will have to change every category
column in your posts
table. If you normalize, you will only need to change one row in your categories
table, and change that Car
to Sedan
and all your posts will show the updated category name.
Example posts
table:
id | catid | title | content | date
1 | 1 | something about cars | the content of the post | 2013-10-01
Example categories
table:
id | name
1 | Car
2 | Truck
3 | Boat
http://en.wikipedia.org/wiki/Database_normalization
If you don't want a normalized database, then in your select dropdown, you pass your catid
, and in your PHP script, get the ID and look for the corresponding category name from the categories
table.
UPDATE
Use MySQL JOIN to get the category name while pulling your post.
To get all posts:
SELECT posts.*, categories.name as category FROM posts p JOIN categories c ON p.catid = c.id
To get a post by ID:
SELECT posts.*, categories.name as category FROM posts p JOIN categories c ON p.catid = c.id WHERE posts.id = YOUR_ID
Then when display your post, you can just do:
echo $post['category']
and it will print out the category name
UPDATE 2
Then do as @jeff says. Put a pipe in your SELECT OPTION values.
<select name="category">
<option value="1|Car">
<option value="2|Truck">
</select>
In your PHP, do the following:
$category = $_POST['category'];
//Explode the category, this will generate an array
$category = explode('|', $category);
//the $category will result in array('1', 'Car')
$cat_id = $category[0];
$cat_name = $category[1];
//Now you have both your category ID and Name
Read up on PHP Explode