douxin8383 2015-12-07 06:46
浏览 209
已采纳

如何添加“选择一个类别”文本以下拉选项列表?

Here is a code for selecting a category and then another piece of code inserts it in database it works fine but now I want to have a Select a category... row above all categories in dropdown box and if submit is clicked without selecting a category div with id='er' should give error message please select a category. So how to add select a category.. text at the top of all options so that it's only a text and not a select option?

<?php
error_reporting('E_ALL ^ E_NOTICE');
if(isset($_POST['submit'])) {
$title=strip_tags($_POST['title']);
$body=strip_tags($_POST['body']);
$category=$_POST['category'];
if (strlen($title) == 0 || strlen($body) == 0){
 $er = "Title and body cannot be empty!";
}
else {
 $stmt = $db->prepare("INSERT INTO posts (title, body category_id) VALUES (:title,:body,:category_id));
 $stmt->execute(array(':title'=>$title,':body'=>$body,':category_id'=>$category));
?>

<form> 
<label>category</label>   
<?php
 $queryy = "SELECT * FROM categories";    
?>
<select name="category">
<?php 
foreach($db->query($queryy)as $row){
echo "<option value='".$row['category_id']."'>".$row['category']." </option>";
}
?>        
</select>
<input type='text' name='title'/>
<input type='text' name='body'/>
<div id="er"><?php echo $er; ?></div></center>
<input type="submit" id="submit" name="submit" value="Save"  />
</form>
  • 写回答

4条回答 默认 最新

  • doulaozhi6835 2015-12-07 06:51
    关注

    Add an <option> above the dynamically generated ones with no value:

    <option value="">Select a category</option>
    

    Then in your PHP you want to check that if $_POST['category] is empty throw an error:

    if (empty($_POST['category'])) {
        $er = "Please select a category from the options";
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器