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>
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";
}
Add following at the top of all <option>
tag
<option value="">Select a category</option>
In you code, like following:
<select name="category">
<option value="">Select a category</option>
<?php
foreach($db->query($queryy)as $row){
echo "<option value='".$row['category_id']."'>".$row['category']." </option>";
}
?>
</select>
Try like this
<select name="category">
<option>Select Category</option> // <--- this line
<?php
foreach($db->query($queryy)as $row){
echo "<option value='".$row['category_id']."'>".$row['category']." </option>";
}
?>
</select>
Try this:
<select name="category">
<option value="">Select Category</option>
<?php foreach($db->query($queryy)as $row){
echo "<option value='".$row['category_id']."'>".$row['category']." </option>";
}
?>
</select>