How to used selected in dropdown list - php

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>

Related

User form-data to update query PHP

I have basic question about storing $variable data and later use in html script, anyone who can help me? Right now, the variable $gset is not stored.
<?php
// Update Strictness value
if(isset($_POST['strictness'])){
$gset = $_POST['strictness'];
$strictnessUpdate = "UPDATE users SET strictness = '$gset' WHERE user_id = 1";
mysqli_query($conn, $strictnessUpdate);
echo "strictness value updated";
}
?>
<form method="POST" class="form-align" action="">
<h5 class="my-6">Current Strictness :</h5> <?php echo $gset; ?><br>
<select name="strictness" required>
<option value=""></option>
<option value="15">15</option>
<option value="31">31</option>
</select>
<input type="submit" name="substrict" value="CHANGE">
</form>
<?php
$_grabStrictness ="SELECT strictness FROM users WHERE id = 1";
$gs_query = mysqli_query($conn, $_grabStrictness);
$gs_result = mysqli_fetch_array($gs_query);
if ($gs_result > 0) {
while ($result = mysqli_fetch_array($gs_query)) {
$gset = $result['strictness'];
}
}
if(isset($_POST['strictness'])){
$gset = $_POST['strictness'];
$strictnessUpdate = "UPDATE users SET strictness = '$gset' WHERE user_id = 1";
mysqli_query($conn, $strictnessUpdate);
echo "strictness value updated";
}
?>
<form method="POST" class="form-align" action="setStrictness(<?php $conn ?>)">
<h5 class="my-6">Current Strictness :</h5> <?php echo $gset; ?><br>
<select name="strictness" required>
<option value=""></option>
<option value="15">15</option>
<option value="31">31</option>
</select>
<input type="submit" name="substrict" value="CHANGE">
</form>

Form isn't showing select dropdown after validation error

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>

How to echo the selected value from an array fetched from the database

I want to echo the selected value from the database to update it then store it
for example I have an asset with category printers from table category which contains other categories and when I want to edit this asset on the edit page I should get a dropdown list contains all the categories and selected on printers then if I want to change it I will if not leave unchanged
The array is drop-down from table category inner joined with user_asset table in the database by asset_category as a foreign key
this is what I have done so far
<label for="basicinput">الصنف : </label>
<?php
$result = mysqli_query($conn, "SELECT * FROM category");
?>
<select name="asset_category" class="form-control" required>
<?php while( $row = mysqli_fetch_array($result)) {?>
<option value="<?php echo $row['category_id'];?>">
<?php echo $row['cate_name'];?>
</option>
<?php }?>
</select>
</div>
You can add if check if ($row['cate_name'] == 'computer') { ?> and then add selected to this option:
<label for="basicinput">الصنف : </label>
<?php
$result = mysqli_query($conn, "SELECT * FROM category");
?>
<select name="asset_category" class="form-control" required >
<?php while( $row = mysqli_fetch_array($result)) {
if ($row['cate_name'] == 'computer') { ?>
<option value="<?php echo $row['category_id'];?>" selected><?php echo $row['cate_name'];?></option>
<?php } else { ?>
<option value="<?php echo $row['category_id'];?>"><?php echo $row['cate_name'];?></option>
<?php }
}?>
</select>
Notice: If you have multiple elements with that category it will select the last one.
the answer is very simple.. let's put this code
<label for="basicinput">الصنف : </label>
<?php
$result = mysqli_query($conn, "SELECT * FROM category");
?>
<select name="asset_category" class="form-control" required>
<?php while( $row = mysqli_fetch_array($result)) {
if($row['cate_name']== printers) { ?>
<option value="<?php echo $row['category_id'];?>" selected="selected">
<?php echo $row['cate_name'];?> </option>
<?php } else { ?>
<option value="<?php echo $row['category_id'];?>">
<?php echo $row['cate_name'];?> </option>
<?php }?>
</select>
</div>
The logic is that using while loop, checking the condition using if class, and when it satisfies make it as selected. Then it will be echo as selected Value.

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>

Populating select box with existing value

I have created a form which allows users to edit existing data within a database, I pull information from one page to the next to populate text boxes and select boxes. I have managed to populate the select box with the correct value but when the update statement goes through it deletes or doesn't recognize the pre-existing value. Can anyone help?
if (isset($_POST['submit'])) {
// Process the form
if (empty($errors)) {
$id = $brand["brandId"];
$brandName = mysql_prep($_POST["brandName"]);
$brandCategory = mysql_prep($_POST["brandCategory"]);
$brandKeyword = mysql_prep($_POST["brandKeyword"]);
$addedBy = mysql_prep($_SESSION['username']);
$query = "UPDATE brands SET ";
$query .= "brandName = '{$brandName}', ";
$query .= "brandCategory = '{$brandCategory}', ";
$query .= "brandKeyword = '{$brandKeyword}', ";
$query .= "addedBy = '{$addedBy}', ";
$query .= "dateTime = CURRENT_TIMESTAMP ";
$query .= "WHERE brandId = '{$id}' ";
$query .= "LIMIT 1";
$result = mysqli_query($connection, $query);
if ($result && mysqli_affected_rows($connection) == 1) {
// Success
$_SESSION["message"] = "Brand updated.";
redirect_to("search.php");
} else {
// Failure
$_SESSION["message"] = "Brand update failed.";
}
}
} else {
// This is probably a GET request
} // end: if (isset($_POST['submit']))
?>
<?php $layout_context = "user"; ?>
<?php include("../includes/layouts/header.php"); ?>
<?php include("../includes/layouts/navigation.php"); ?>
<div class="section">
<div id="message">
<?php echo message(); ?>
<?php echo form_errors($errors); ?>
</div>
<form id="edit_brands" action="edit_brands.php?id=<?php echo urlencode($brand["brandId"]); ?>" method="post">
<h2>Edit Brand Information: <?php echo htmlentities($brand["brandName"]);?></h2>
<p>
<label for="bname">Brand Name:</label>
<input class="textbox" id="bname" type="text" name="brandName" value="<?php echo htmlentities($brand["brandName"]); ?>" autofocus/>
</p>
<p>
<label for="bcategory">Brand Category:</label>
<select class="textbox" id="bcategory" type="text" name="brandCategory">
<option value=""><?php echo htmlentities($brand["brandCategory"]); ?></option>
<option value="Animation">Animation</option>
<option value="Automotive">Automotive</option>
<option value="Beauty and Fashion">Beauty & Fashion</option>
<option value="Comedy">Comedy</option>
<option value="Cooking and Health">Cooking & Health</option>
<option value="DIY">DIY</option>
<option value="Fashion">Fashion</option>
<option value="Film and Entertainment">Film & Entertainment</option>
<option value="Food and Drink">Food & Drink</option>
<option value="Gaming">Gaming</option>
<option value="Lifestyle">Lifestyle</option>
<option value="Music">Music</option>
<option value="News and Politics">News & Politics</option>
<option value="Science&Education">Science & Education</option>
<option value="Sports">Sports</option>
<option value="Technology">Technology</option>
<option value="Television">Television</option>
</select>
</p>
<p>
<label for="bkeyword">Brand Keyword:</label>
<textarea class="FormElement" id="bkeyword" name="brandKeyword" id="brandKeyword" placeholder=""><?php echo htmlentities($brand["brandKeyword"]); ?></textarea>
</p>
<p>
<input type="submit" class="button" name="submit" value="Edit Brand" onclick="return confirm('Do you wish to edit brand?');"/>
</p>
<p>
Cancel
</p>
</form>
</div>
</div>
The best way is to build the select from an array.
For instance:
<?php
$array = array('Animation', 'Automotive', 'Beauty and Fashion ', ...);
echo '<select class="textbox" id="bcategory" type="text" name="brandCategory">';
foreach ($array as $value){
if($value == htmlentities($brand["brandCategory"]){
echo '<option value='.$value.' selected>'.$value.'</option>';
}else{
echo '<option value='.$value.'>'.$value.'</option>';
}
}
echo '</select>;
This way you can check if the value in the array is the same that the one recieved by post and then add the selected attribute to the option tag.

Categories