Form isn't showing select dropdown after validation error - php

In my form, I generate the select options from my MySQL data table. But when I submit the form without any value, it returns to a blank page and does not show any validation error. When I select a value and submit the form, it inserts the value to MySQL table. No MySQL or PHP error is thrown. I am assuming the problem is the query for the select option is not running. But if it is the problem, what should be the good practice to avoid this problem?
My form is:
<?php
require 'db.php';
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$ad_di = "";
$ad_di_err = "";
if (empty(trim($_POST["ad_di"]))) {
$ad_di_err = "District cannot be empty.";
} else {
$ad_di = trim($_POST["ad_di"]);
}
if (empty($ad_di_err)) {
$sql = "INSERT INTO address (ad_di) VALUES (?)";
if ($stmt = $mysqli->prepare($sql)) {
$stmt->bind_param("i", $p_ad_di);
$p_ad_di = $ad_di;
if ($stmt->execute()) {
$id = $mysqli->insert_id;
header("location: add.php?id=$id&update=success");
}
$stmt->close();
}
}
}
?>
<form id="acEdit" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post" class="contact-form">
<div class="row">
<div class="col-3">
<div class="form-group">
<label>District</label>
<select name='ad_di' id='ad_di' class='custom-select'>
<option value=''>Select one ...</option>
<?php
$qDistrict = "SELECT * FROM districts order by name ASC";
echo "<select name='ad_di' id='ad_di' class='custom-select'><option value=''>Select one ...</option>";
foreach ($mysqli->query($qDistrict) as $rowDistrict) {
echo "<option value={$rowDistrict['id']}>{$rowDistrict['name']}</option>";
}
echo "</select>";
?>
</select>
<span class="invalid-feedback"><?php echo $ad_di_err; ?></span>
</div>
</div>
</div>
</form>
The above query for select options returns as following when the page is loaded first,
<select name="ad_di" id="ad_di" class="custom-select">
<option value="">Select one ...</option>
<option value="28">Dist A</option>
<option value="11">Dist B</option>
<option value="35">Dist C</option>
<option value="33">Dist D</option>
</select>
But when the validation error occurs, the returning page doesn't have any options, just returns
<select name="ad_di" id="ad_di" class="custom-select">
<option value="">Select one ...</option>
</select>

Related

Search form with PHP and PDO then display results on page

I am trying to search my SQL database with a simple search form and then return the data to the screen.
For example, the user can select a year, then all the row results from the table display all of the information for that entry. Here is my form:
<form class="" method="POST" action="availability.php" enctype="multipart/form-data">
<select class="form-control mb-3" name="year" id="year">
<option disabled selected>Year</option>
<option value="2019">2019</option>
<option value="2020">2020</option>
<option value="2021">2021</option>
</select>
<input class="btn btn-blue-grey" type="submit" value="submit">Search
<i class="fas fa-search ml-1"></i>
</input>
</form>
And here is my PHP
if(isset($_POST['submit'])) {
$year = $_POST['year'];
var_dump($year);
var_dump($_POST);
$sql = "SELECT * FROM availability WHERE year = :year";
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':year',$year,PDO::PARAM_STR);
$stmt->setFetchMode(PDO::FETCH_ASSOC);
$stmt->execute();
$data = $stmt->fetchAll(); }
and my HTML
<ul>
<?php foreach($data as $stmt) { ?>
<li><?php echo $stmt['cruise'];?></li>
<li><?php echo $stmt['year'];?></li>
<?php } ?>
</ul>
At the minute, the form submits, but I get nothing populating the list.. Any help would be appreciated.
You can try to use this query :
$year = $_POST['year'];
$sql = "SELECT * FROM availability WHERE year = :year";
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':year',$year,PDO::PARAM_STR);
$stmt->setFetchMode(PDO::FETCH_ASSOC);
$stmt->execute();
$data = $stmt->fetchAll();
$stmt->bindParam(':year',$year,PDO::PARAM_STR); <-- does this need to be PARAM_INT ?
also have you var_dump'ed $year = $_POST['year']; to make sure you are getting a value?
You could turn on error_reporting and see if you get any useful errors
you must change a few thing,
first, edit the select tag to:
<select class="form-control mb-3" name="year" id="year">
<option disabled selected>Year</option>
<option value="2019">2019</option>
<option value="2020">2020</option>
<option value="2021">2021</option>
</select>
There is a condition that seems it is wrong.
so, change your html code to
if($_POST) {
$year = $_POST['year'];
$stmt = $pdo->prepare("SELECT * FROM availability WHERE year = :year");
$stmt->execute(array("%$year%"));
// fetching rows into array
$data = $stmt->fetchAll();}

Multiple search value using dropdown list in PHP and MySQL

Html Form:
<form>
<select name="country[]" id="country" multiple>
<option value="any">any</option>
<option value="India">India</option>
<option value="Canada">Canada</option>
<option value="UK">UK</option>
<option value="USA">USA</option>
<option value="Australia">Australia</option>
</select>
</form>
PHP Code
<?php
$country = $_REQUEST['country'];
if($country=="")
$countrysql = "";
else
{
if($country == "Any") $countrysql = "";
else
{
$country = str_replace(",","','",$country);
$countrysql = " and Country in ('$country')";
}
}
$queryString = "SELECT * FROM register where $countrysql";
?>
I have created a form in PHP and I want to search multiple options. I already created table Register and a column Country. I am getting the result If I give single value. If I give multiple I am not getting the result. Please help.
You evaluate in if($country == "Any") the word Any is not equal to any in option <option value="any">any</option>
But I suggest this php code:
<?php
$country="";
$countryError="";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["country"])){
$countryError = "Country is required";
}else{
$country = $_POST["country"];
}
if($country == "Any") {
$queryString = "SELECT * FROM register";
}else{
$queryString = "SELECT * FROM register where Country in ('$country')";
}
// Print the SQL string:
echo $queryString;
}
?>
The html tags:
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<select name="country" id="country" multiple>
<option value="Any">any</option>
<option value="India">India</option>
<option value="Canada">Canada</option>
<option value="UK">UK</option>
<option value="USA">USA</option>
<option value="Australia">Australia</option>
</select>
<input type="submit" name="submit" value="Submit">
</form>
<span class="error"><?php echo $countryError;?></span>

How to used selected in dropdown list

i dont know exactly how i am supposed to explain my question. but i'll try my best. Im currently trying to make an update form. when user clicked on the edit icon they will be directed to the edit form and the value are carried. i used 'typeid' to carry the values. im having problem with my drop down. i used selected but the value duplicate.
dropdown
so im trying to solve this, but know idea how to solve it. i have to used php only and i am not an expert of php.
if (isset($_GET['typeid'])) {
$sql = "SELECT * FROM vehicletype WHERE id_vehicleType=" . $_GET['typeid'];
$result = mysqli_query($link, $sql);
$row = mysqli_fetch_array($result);
if($row['status_vehicleType']==1){
$status = "Enabled";
}
else{
$status = "Disabled";
}
}
above are the typeid that i used to carry the values.
<div class="form-group">
<label>Choose Vehicle Type Status</label>
<select class="form-control" name="status" required class="form-control" value="<? php if(isset($row['status_vehicleType'])){ echo $status; } ?>">
<option value="">Select Vehicle Type</option>
<option value=<?php echo $row['status_vehicleType']; ?> <?php if($_GET["typeid"]==$row['status_vehicleType']){ ?> selected <?php } ?> ><?php echo $status; ?></option>
<option value="1">Enabled</option>
<option value="0">Disabled</option>
</select>
Here is simple answer for this question
if you have any other questions freely ask me thanks
<?php
function selected($x, $y) {
if ($x == $y) {
return " selected";
} else {
return "";
}
}
$sql = "SELECT * FROM vehicletype WHERE id_vehicleType=" . $_GET['typeid'];
$result = mysqli_query($link, $sql);
$row = mysqli_fetch_array($result);
$q_status = $row['status_vehicleType'] ;
?>
<div class="form-group">
<label class="control-label text-inverse" for="name">Status</label>
<select class="form-control" name="q_status" id="q_status" required="" autocomplete="off" >
<option value="1" <?php echo selected($q_status,"1");?> >Enabled</option>
<option value="0" <?php echo selected($q_status,"0");?> >Disabled</option>
</select>
</div>
use below code, (for testing set $_GET['typeid']=somevalue):
$row=array();
if (isset($_GET['typeid'])) {
$sql = "SELECT * FROM vehicletype WHERE id_vehicleType=" . $_GET['typeid'];
$result = mysqli_query($link, $sql);
$row = mysqli_fetch_array($result);
}
<div class="form-group">
<label>Choose Vehicle Type Status</label>
<select class="form-control" name="status" required class="form-control">
<option value="">Select Vehicle Type</option>
<option value="1" <?php if($row['status_vehicleType']==1){?>selected<?php }?>>Enabled</option>
<option value="0" <?php if($row['status_vehicleType']==0){?>selected<?php }?>>Disabled</option>
</select>

php html select value

I have a select box connect to database for countries, it works but trying to keep the selected data in the form clears itself out. I have tried adding a selected but gives error
<div class="form-group">
<label>Country</label>
<?php
$sql = "SELECT * FROM countries ";
$result = query($sql);
?>
<select class="form-control input-lg box" id="country" name="country">
<option value="">Select a country</option>
<?php
$i = 0;
while (($row = mysqli_fetch_assoc($result)) != false) {
?>
<option value="<?=$row["country_id"];?>"><?=$row["country_name"];?></option>
<?php
$i ++;
}
?>
</select>
</div>
Assign the return value of a ternary operator to the variable $selected and add it to the option tag
<?php
$selected = ($_POST['country'] == $row["country_id"])?"selected":"";
?>
<option value="<?=$row["country_id"];?>" <?=$selected ?>>
<?=$row["country_name"];?>
</option>

php mysql search using boxlist

I am looking for a way to search for data from the database using input type box list, I tried make the code but it doesn't display anything:
html code:
<form action="users.php" method="post" name="searching">
<select name="users">
<option selected="selected" value="">-- select --</option>
<option value="1">user1</option>
<option value="2">user2</option>
<option value="3">user3</option>
</select>
<input type="submit" name="search" value="find">
</form>
php code:
if (isset($_POST['users'])) {
$key = trim ($_POST['users']);
$s = "SELECT * FROM users where user_name LIKE '%$key %'";
$res = mysql_query($s) or die('query did not work');
while($row = mysql_fetch_array( $res ))
{
?>
User ID: <?php echo $row['user_id'] ?>
User Name: <?php echo $row['user_name'] ?>
<?php
}
?>
when I try the code I didn't get any result and when I remove the while loop and put this instead of it :
<?php echo $key; ?>
it gives me the numbers of the selected value, for example if I select user2 the result will be 2. and I want the result to be user id and user name.
you need to fetch all the user name in your drop down select box
<select name="users">
<option selected="selected" value="">-- select --</option>
<?php $s2 = "SELECT * FROM users";
$q2=mysql_query($s2) or die($s2);
while($rw=mysql_fetch_array($q2))
{
echo '<option value="'.$rw['userid'].'">'.$rw['username'].'</option>';
}</select>
?>
<?php if (isset($_POST['search'])) { // submit button name here
$key = $_POST['users'];
$s = "SELECT * FROM users where user_id='".$key."'";
$res = mysql_query($s) or die($s);
while($row = mysql_fetch_array( $res ))
{
?>
User ID: <?php echo $row['user_id'] ?>
User Name: <?php echo $row['user_name'] ?>
<?php
}
?>
edit your html to this,you will get the in $_POST which will be in value='something'
<form action="users.php" method="post" name="searching">
<select name="users">
<option selected="selected" value="">-- select --</option>
<option value="user1">user1</option>
<option value="user2">user2</option>
<option value="user3">user3</option>
</select>
<input type="submit" name="search" value="find">
</form>
Or if value is the id of user then change query to this
$s = "SELECT * FROM users where user_id='".$key."'";

Categories