PHP - SAVE select option value AFTER submission - php

I have a drop down menu which lists the associated 'IDs' from the mysql database:
<fieldset>
<legend><strong>Change ID:</strong></legend>
<?php
$hostname = "localhost";
$username = "root";
$password = "";
$databaseName = "change_management";
$connect = mysqli_connect($hostname, $username, $password, $databaseName);
$query3 = "SELECT `change_id` FROM `change_request_tbl` WHERE (approval_disposition LIKE 'Requires Editing')";
$result3 = mysqli_query($connect,$query3);
?>
<select required name="change_id">
<option value="">Please specify...
<?php
while ($roww = mysqli_fetch_array($result3))
{
echo "<option value='".$roww['change_id']."'>".$roww['change_id']."</option>";
}
?>
</select>
<input type="submit" name="get" value="Get Details" class="btn">
</fieldset><br><br><br>
When the user clicks "Get Details" the dropdown reverts back to "Please specify". I have found many examples of how to save the value after submission, but none seem to be applicable to my code as I am fetching values from the database.
Is there anyway to save the last inputted values in this current format?

When the user submits the form, the form value change_id has the value you're looking for. So when populating your option elements you can check if any of them match what was submitted and set it to be selected. Something like this:
if (isset($_POST['change_id']) && $roww['change_id'] == $_POST['change_id']) {
echo "<option selected value='".$roww['change_id']."'>".$roww['change_id']."</option>";
} else {
echo "<option value='".$roww['change_id']."'>".$roww['change_id']."</option>";
}
Or if you want it all on one line (using the ternary conditional operator):
echo "<option ".((isset($_POST['change_id']) && $roww['change_id'] == $_POST['change_id']) ? "selected" : "")." value='".$roww['change_id']."'>".$roww['change_id']."</option>";

Related

How to pass the dropdown list selected value from a php form to a mysql query

The function of this web application is to: select a customer from the dropdown list (the dropdown list values are auto popup from the database), it will print the selected customer name and its postcode on the result page.
When I choose the customer name from the dropdown list and click the submit button, the result page only prints the $customerv value (the 1st echo), but the $result value (2nd echo) was not printed. The customer name is unique in the database.
index.php:
<?php
require_once('config.php');
?>
<!DOCTYPE HTML>
<html>
<form action="result.php" method="post">
Customer:<br>
<select Customer id="customer" name="Customer">
<option value="">--- Select Customer ---</option>
<?php
$sql = "SELECT b.BPName from BP b where b.BPCode like 'C%' Order by b.BPName";
$customer = mysqli_query($conn, $sql);
while ($cat = mysqli_fetch_array(
$customer,
MYSQLI_ASSOC
)) :;
?>
<option value="<?php echo $cat['BPName']; ?>">
<?php echo $cat['BPName']; ?>
</option>
<?php
endwhile;
?>
</select>
<input type="submit" value="Submit">
</form>
</html>
config.php:
<?php
$servername = "localhost";
$username = "xxx";
$password = "xxx";
$databse = "xxx";
$conn = new mysqli($servername, $username, $password, $databse);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
?>
result.php:
<table>
<?php
require_once('config.php');
$customerv = $_POST['Customer'];
echo $customerv;
$sql = "SELECT shiptozipcode FROM BP WHERE BPName ='$customerv'";
$result = $conn->query($sql);
echo $result;
?>
</table>
The query result itself isn't something that's "printable" to the page. It's not just a single value, it's a complex object. You need to fetch the record(s) from the result. For example:
$result = $conn->query($sql);
while ($row = $result->fetch_assoc()) {
echo $row["shiptozipcode"];
}
If you're sure there will be only one row (it's still a good idea to add some error checking anyway) then you don't need the loop:
$result = $conn->query($sql);
$row = $result->fetch_assoc();
echo $row["shiptozipcode"];
But either way, you need to extract the data from the result set. (You could also use fetch_object() instead of fetch_assoc() if you prefer object syntax over array syntax.)
As an aside, be aware that your query is wide open to SQL injection. Now would be a good time to learn how to correct that.

How can I populate a 3rd column result on intersections of 1st and 2nd columns all from the same table that are selected by the user on dropdown?

I have a column vehicle_name and I would like 2 dropdown lists of my 2 other columns namely, vehicle_type and vehicle_color.
When these 2 dropdown values are selected and submitted, I would like their intersection to print out the values from vehicle_name. So far my code only generates a dropdown list for vehicle_type, I would need another dropdown for vehicle_colour. Which on submissions populates the intersected values for the vehicle_name. How can I achieve this?
<!DOCTYPE html>
<html>
<body>
<?php
echo "<br>";
echo "<br>";
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "mydb";
$db = new mysqli($servername, $username, $password, $dbname);
if (!$db) {
exit('Connect Error (' . mysqli_connect_errno() . ') '
. mysqli_connect_error());
}
?>
<br>
<div class="label">Select vehicle type:</div>
<select name="payment_method">
<option value = "">---Select---</option>
<?php
$queryusers = "SELECT DISTINCT vehicle_type FROM orders";
$db = mysqli_query($db, $queryusers);
while ($d=mysqli_fetch_assoc($db)) {
echo "<option value='{".$d['vehicle_type']."}'>".$d['vehicle_type']."</option>";
}
?>
</select>
<br>
<div class="label_for_time">Select color:</div>
<select name="vehicle_color">
<option value = "">---Select---</option>
<?php
$query_for_color = "SELECT DISTINCT vehicle_color FROM orders";
$db = mysqli_query($db, $query_for_date);
while ($a=mysqli_fetch_assoc($db)) {
echo "<option value='{".$a['vehicle_color']."}'>".$a['vehicle_color']."</option>";
}
?>
</select>
<br>
<br>
<button class="go-btn" type="submit">Go</button>
</body>
</html>
As I don't see any AJAX / client-side code in your above example I assume that this is a pure backend-side filtering you are performing. Your code is currently missing parts of the required elements we would need but let's try to figure this out together:
1. Form around your inputs
Add a <form method="POST" target="path-to-your-script.php"> where "path-to-your-script.php" has to be changed to your PHP file name or rewritten URL path. This has to be around the <select> boxes.
You may also use PHP_SELF to set this automatically, this should work in most cases. I used html_entities($var) to avoid any code injections via manipulated URL.
<form name="test" action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>" method="post">
2. Check for POST'ed variable 'vehicle_type'
In your form, check if a search for available colors has been performed:
<?php
$query_for_color = "SELECT DISTINCT vehicle_color FROM orders";
// check if the form variable 'vehicle_type' is available; if so, filter entries.
if (isset($_POST['vehicle_type'])) {
$vType= filter_var($_POST['vehicle_type'], FILTER_SANITIZE_STRING);
$query_for_colors .= ' WHERE vehicle_type = \''.$vType.'\'';
}
$db = mysqli_query($db, $query_for_date);
while ($a=mysqli_fetch_assoc($db)) {
echo "<option value='{".$a['vehicle_color']."}'>".$a['vehicle_color']."</option>";
}
?>
Edit:
As pointed out by one user in the comment, filter_var($var, FILTER_SANITIZE_STRING) won't be enough to avoid potential SQL injections. This was just a recommendation and was not part of the question at all. If you have to work with user data, do more than using filter_var(), instead use either prepared statements or properly escape the user data. There are many tutorials like this one out there that will guide you to safe queries.

Using data in <select> options in MySQL query

I would like to delete a row from an MySQL database. The row that I'd like to delete is displayed in a box, with each being obtained via a loop and SELECT statement.
I've already got the rows in the database being displayed accordingly; however, I'd like a button that once pressed, would delete the selected option from the database.
Here is my current code:
<form action="" method="post">
<label>Patient Name:</label>
<br><br>
<select name="patient" id="patient">
<?php
$conn = new mysqli("localhost", "root", "", "as2");
$result = $conn->query("SELECT patientID, patientName, address FROM patient ORDER BY patientName ASC");
while ($row = $result->fetch_assoc()){
$patientName = $row['patientName'];
$address = $row['address'];
echo "<option value=\"patient\">" .$patientName. ", ".$address."</option>";
}
?>
</select>
<input type="submit" name="delete" value="Delete Record">
</form>
How would I go about making the "Delete Record" button delete the selected option from the database?
first record (patientID) in a string
$patientID = $row['patientID'];
then Add $patientIDto (option value) so it become :
echo "<option value=".$patientID.">" .$patientName. ", ".$address."</option>";
then add this code After everything (ofc outside the "while" loop) :
<?php
$selected_patient = $_POST['patient'];
if( $_SERVER['REQUEST_METHOD'] === 'POST'
&& isset($_POST['delete']) && isset($_POST['patient']) ) {
if( !empty($_POST['patient']) ){
$patient_ID = mysql_real_escape_string($selected_patient);
if ( $conn->query("DELETE FROM patient WHERE patientID={$patient_ID}") )
echo "user has been deleted successfully";
else
echo "Error deleting";
}
}
?>
now you'r good to go , after click delete button refresh your page and Boom! , the user will Disappears
and if you want a real time Action u can use (Ajax)
Try this
while ($row = $result->fetch_assoc()){
$patientName = $row['patientName'];
$address = $row['address'];
$patientID = $row['patientID']; //get patient id
echo "<option value=\"$patientID\">" .$patientName. ", ".$address."</option>"; // change in option value
}
Now on form submit, you will get patient id in $_POST['patient'] , can write your delete query.
Hope this will hope.

Show existing value as pre-selected in drop down, radio buttons and checkboxes fields

I have a network that I am building which groups freelancers together and allows potential customers to browse a profile containing their details.
In my database I store some values that the user will enter via a form using drop down or radio/checkbox fields. Through an edit page they can amend that data.
I'm struggling with how to get those fields pre-populated (if the value exists in the DB) with the value they've already made, probably at the time of creating their profile. I have managed to do it with the regular text/input fields by echoing out the column value as a form field value but can't figure out how to achieve it with these other fields.
UPDATE: I need to pull the value from the database and have the form fields show that as the pre-selected/default entry.
If I leave them blank it means the user will overwrite any existing data with nothing and in erase anything they've entered for that field before.
An example drop down field is below;
<div class="item-content">
<div>Experience</div>
<select class="form-control" name="profile_experience" id="profile_experience">
<option value="1">Amateur</option>
<option value="2">Semi Professional</option>
<option value="3">Professional</option>
</select>
</div>
I'm fetching the values with the following;
<?php
$id=$_SESSION['user']['id'];
$result = $db->prepare("SELECT * FROM profiles WHERE user_id= :userid");
$result->bindParam(':userid', $id);
$result->execute();
for($i=0; $currentprofile = $result->fetch(); $i++){
?>
<!--FORM HERE-->
<?php
}
?>
Retrieve and stote the stored values
<?php
$query = "SELECT id FROM Tablename WHERE YOUR_CONDITION";
$result = mysqli_query($connection, $query);
if (mysqli_num_rows($result) > 0)
{
$row = mysqli_fetch_assoc($result);
$selectedOption = $row['id'];
}
else
{
$selectedOption = ''; // Your default selection of $cc
}
$profile_experience_array = array(1=>'Amateur',
2=>'Semi Professional',
3=>'Professional');
?>
The below code displays all the options of profile_experience_array. $key will check with the database value ($selectedOption) and that text will get selected by default.
<div class="item-content">
<div>Experience</div>
<select class="form-control" name="profile_experience" id="profile_experience">
<option value="0">Select</option>
<?php
foreach ($profile_experience_array as $key => $text)
{
if ($key == $selectedOption)
{
echo '<option value="'.$key.'" selected="selected">'.trim($text).'</option>';
}
else
{
echo '<option value="'.$key.'">'.trim($text).'</option>';
}
}
?>
</select>
</div>

Add Item Drop Down List

I have a drop down list which i filled with items from my database "mydatabase".
connect.php
<?php
$dbname = 'mydatabase';
$dbuser = 'louie';
$dbpass = '';
?>
mydatabase contains the table 'Users' with 'Name' and 'NameID' column.
index.php
<?php
include ("connect.php");
$mysqli = new mysqli("localhost", $dbuser, $dbpass, $dbname);
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
?>
<div class="label">Select Name:</div>
<select name="names" onchange="change(this.value)">
<option value = "none">---Select---</option>
<?php
$query = "SELECT `Name` FROM `Users`";
$mysqli = mysqli_query($mysqli, $query);
while ($d=mysqli_fetch_assoc($mysqli)) {
echo "<option value='{".$d['Name']."}'>".$d['Name']."</option>";
}
?>
</select>
<select name="nid" id="nameid">
</select>
In my name column there is two values. Louie and Jane which fills the first dropdown "names". What I want to do is whenever I select the Louie, the second drop down with the id 'nameid' will be filled with the NameID column from my database.
I've got some idea in disabling the second drop down but without the database.
<script>
function change(value) {
if(value=="none")
document.getElementById("nameid").disabled=true;
else
document.getElementById("nameid").disabled=false;
}
</script>
But I don't know how to fill the second dropdown with NameID column by selecting the Louie in first drop down.
try something like this:
var x = document.createElement("OPTION");
x.text = value;
var s = document.getElementById("nameid");
s.add(x);
The trick here is to understand that only PHP can access your database, and that reacting on UI changes is a javascript issue. That means that if you want the nameID on your second dropdown, php first needs to already provide it somewhere, and next you'll need some javascript to actually show it.
This is a possible solution:
<!-- note I changed the function onchange="change(this.value)" to onchange="change(this)"
because this.value is actually not the value.. -->
<select name="names" onchange="change(this)">
<option value = "none">---Select---</option>
<?php
// Select both columns you want to use in PHP
$query = "SELECT `NameID`, `Name` FROM `Users`";
$mysqli = mysqli_query($mysqli, $query);
// I used the value field to hold the id, rather than the name, while the name is shown to the user.
while ($d=mysqli_fetch_assoc($mysqli)) {
echo "<option value='".$d['NameID']."'>".$d['Name']."</option>";
}
// your other code...
?>
<script>
function change(oSelect) {
var value = oSelect.options[oSelect.selectedIndex].value;
var name = oSelect.options[oSelect.selectedIndex].innerHTML;
if(name=="Louie") {
document.getElementById('nameid').innerHTML = "";
for (var i=0; i<oSelect.options; i++) {
document.getElementById('nameid').innerHTML += "<option value='"+oSelect.options[i].value+"'>"+oSelect.options[i].value+"</option>";
}
}
}
</script>

Categories