Reputation: 15
I'm trying to make a selection form that submits to a database, but the problem is when the selection is not selected it will still submit the empty value to the database. Is there a way to ignore an empty selection form when it's empty when the submit button is clicked or when the page is reloaded?
Here is the code that I have been working on
<?php
//DB Connection
$mysqli = new MySQLi('localhost','root','','mrbs');
$resultSet = $mysqli->query("SELECT * FROM mrbs_users");
//White board Current PIC
$wb_current_pic = $mysqli->query("SELECT * FROM mrbs_room_pic WHERE id='1'");
$wb_search_pic = $wb_current_pic->fetch_assoc();
$wb_pic = $wb_search_pic['name'];
?>
<form action="" method="post">
<div>
White Board (Current PIC : <?php echo("$wb_pic");?>)
<div>
<select name="white_board">
<?php
//echo "<option value=''>--set---</option>";
echo "<option value='' disabled selected>---set---</option>";
while($rows = $resultSet->fetch_assoc()){
$username = $rows['name'];
$user_email = $rows['email'];
echo "<option value='$user_email $username'>$username</option>";
}
?>
</select><br>
</div>
</div>
<input type="submit" name="button" value="Submit"/>
</form>
<?php
$wb_str = $_POST['white_board'];
//string processing
$wb_arr = explode(" ",$wb_str);
$wb_pic_email = $wb_arr['0'];
$wb_pic_name = $wb_arr['1'];
echo '<b>The PIC Adresses:</b>' .'<br>' .
$wb_pic_email . " " .$wb_pic_name .'<br>';
//UPDATE DB
$ex_query_wb = "UPDATE mrbs_room_pic SET name = '$wb_pic_name', email = '$wb_pic_email' WHERE id ='1'";
mysqli_query($mysqli,$ex_query_wb);
?>
Based on the code, did I do something wrong? Or is there a better way to do this?
Upvotes: 0
Views: 71
Reputation: 458
You should wrap your database query in a clause that checks that the strings are not empty, e.g.
// Use trim to remove any whitespace
if (trim($_POST['white_board']) === '') {
// Tell the user to check their data
} else {
// Do query...
}
On a related note, I'd also suggest looking at sanitising and validating user input, and also consider using PDO instead of mysqli_query as it provides better protection against SQL injection. Your query is extremely vulnerable.
Upvotes: 2