Umme Habiba Kanta
Umme Habiba Kanta

Reputation: 163

php get id from html select

my html form is bellow and process this page with add_post_process.php. In this page i insert the data to mysql database in table name "user_post"

Well, i can insert the all data to mysql database but can't insert cat_id. How can i get this cat_id from my html form? if you need add_post_process.php code then i'll post this. Thanks.

"user_post" table structure:

post_id
user_id
subject
image
img_name
message
cat_id
cat_name
comment_count
poster
date

<form action="add_post_process.php" method="post" name="addpost" 
enctype="multipart/form-data"> 
<select name="cat_name" class="tdpost">
<?php   
while($row = mysql_fetch_assoc($sql))
{
$cat_name = $row['cat_name'];
$cat_id = $row['cat_id'];
echo "<option value='$cat_name'>$cat_name</option>";
}
?>  
</select></td>
</tr>    
<td>&nbsp;</td>
<td><input type="submit" name="submit" value="Add Post" class="submit" />&nbsp;&nbsp;
<input type="reset" name="clear" value="Clear" class="submit" /></td>
</tr>
</table>
</form>

Upvotes: 1

Views: 10997

Answers (1)

matino
matino

Reputation: 17725

It's the value of the HTML form element that is submitted - I guess you wanted to write echo "<option value='$cat_id'>$cat_name</option>";. Below you can find shorter and cleaner code:

<?php while($row = mysql_fetch_assoc($sql)) : ?>
   <option value="<?php echo $row['cat_id'] . '|' . $row['cat_name'] ?>"><?php echo $row['cat_name'] ?></option>
<php endwhile ?> 

You end up with select like this:

<select name="cat_name">
   <option value="1|category1">category1</option>
   <option value="2|category2">category2</option>
   <option value="3|category3">category3</option>
</select>

Because the whole x|categoryx value will be posted, it's enough to split it by |
Then in your add_post_process.php file do like this:

$cats = explode("|", $_POST['cat_name']);
echo $cats[0]; // cat_id
echo $cats[1]; // cat_name

Upvotes: 4

Related Questions