select option from select box click save button perform database update - php

I have a select box with three options. When an option is selected a save button is then click which performs a database update on the field. This will involve having two submit buttons in one form. I have created a different action on each submit button, this will be the save button:
if ($_POST['update_status'] == 'Save') {
$keys = array_keys($_POST['order_status']);
//perform the database update to change the option value
}
if(isset($_POST['order_selected'])) {
//send email
}
At the moment my select box for each option is embedded in a table like:
echo '<select name="order_status[] id="id"">';
echo '<option value = "Pending" name="order_status['.$i.']" class = "pending"' . ($row['status'] == 'Pending' ? ' selected=selected' : '') . '>Pending</option>';
echo '<option value = "Approved" name="order_status['.$i.']" class = "approved"' . ($row['status'] == 'Approved' ? ' selected=selected' : '') . '>Approved</option>';
echo '<option value = "Disapproved" name="order_status['.$i.']" class ="disapproved"' . ($row['status'] == 'Disapproved' ? ' selected=selected' : '') . '>Disapproved</option>';
echo '</select>';
now at the moment I have the update query working, except it is outside of the form and works by posting a unique order I.D from the database and then performing he update. however I can only do 'approved'. 'pending' is not an issue as I have already set a flag in the database when an order is created, as default pending.
Instead of have this functionality outside of the form, I would like to be apple to select a dropdown item, hit save, and then the database update query is run changing the value in the select box, within the same form, if this would be possible?.
at the moment I have the query and submit button outside of the form which looks like:
<?php
if (!empty($_POST)) {
$id = intval($_POST['approval']);
$query = "UPDATE Orders SET status = 'Approved' WHERE id = $id";
mysql_query($query);
}
$query = "SELECT ID, Orderno, status FROM Orders WHERE status = '0'";
$result = mysql_query($query);
?>
<select name="approval">
<?php while ($row = mysql_fetch_assoc($result)): ?>
<option value="<?php echo $row['ID']; ?>"><?php echo $row['Orderno']; ?></option>
<?php endwhile; ?>
</select>
<input type="submit" action ="" value="Approve Order" />
Many Thanks, any pointers on how I should be tackling this are much appreciated.

I'm pretty confused by your question, but if you are trying to have the database query run without having the user leave the page, and then update the attributes of some of your HTML elements, you are going to have to use AJAX.

Related

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.

PHP/MySQL Auto select option based on previous page

I have a music database with a PHP front end where you can add/edit/delete artists, albums, tracks using the web client. The last real problem I have is getting a select box to automatically select an option I pass to the page.
Example:
On a page called 'createCD.php' I have this code:
echo "<td><a href=\"editCD.php?cdTitle=".rawurlencode($row['cdTitle'])."&cdID=$row[cdID]&artID=$row[artID]&cdGenre=".rawurlencode($row['cdGenre'])."&cdPrice=$row[cdPrice]\" </a>Edit</td>";`
This is used as a link to the next page, and collects all the information about an album in the database and sends in to a page called 'editCD.php'.
Now on this page, all the information is used to fill out the webpage as shown here (there is more but for the purposes of this post, only the first select box matters):
Artist Name:
<!-- dropdown with artist name -->
<?php
echo '<select name= "artID" id="artID">';
while ($row = mysqli_fetch_assoc($result)){
echo '<option value="'.$row['artID'].'">'.$row['artName'].'</option>';
}
echo '</select>';
?>
<p>
Album Title:
<input id="cdTitle" type="text" name="cdTitle" value ="<?php echo htmlspecialchars($cdTitle); ?>" />
</p>
What I would like is for the "selected" option for 'artID' to be the value that is passed to the page. Using the associative array, I was able to display the 'artName' associated with the 'artID'. Currently, all the information about the album appears correctly apart from the 'artName' and it defaults to the first value. This is a problem as if a user simply clicks "Update" it will update the name to the default name, therefore changing the database entry by accident.
I know I need to be using
<option selected ...>
but I'm not sure on the syntax to use.
<?php
$artID = $_GET['artID']; // get the artID from the URL, you should do data validation
echo '<select name= "artID" id="artID">';
while ($row = mysqli_fetch_assoc($result)){
echo '<option value="'.$row['artID'].'"';
if ($artID == $row['artID']) echo ' selected'; // pre-select if $artID is the current artID
echo '>'.$row['artName'].'</option>';
}
echo '</select>';
?>
$artId = $_GET['artID'];
while ($row = mysqli_fetch_assoc($result)) {
$selected = $artId == $row['artID'] ? 'selected' : '';
echo '<option value="'.$row['artID'].'" '.$selected.'>'.$row['artName'].'</option>';
}
First you get the id via $_GET['artID']. (In a real scenario use intval or something to prevent sql injection)
Then check in the loop if the id from database is the same as the id from GET and when it is print "selected, else nothing.

Dropdown menu not displaying change when I change product

I want to access the value selected by user for further processing.
Hence I am using post method to pass the values of whole form.
But GET to access cust_id so that I can reflect change in
further parts of my form. Hence I had to post the following line:
<select id='fullname' onChange="window.location='sp_menu.php?product='+this.value" name='fullname'>
outside php code. But now, once I select some option from dropdown menu, URL changes accordingly, but dropdown menu does not reflects the change
<?php
$query = "SELECT Cust_id, Cust_Name, Cust_City FROM Customers";
$result = mysql_query($query);
?>
<select id='fullname' onChange="window.location='sp_menu.php?product='+this.value" name='fullname'>
<?php
while($row = mysql_fetch_assoc($result)) {
echo '<option value="'.$row['Cust_id'].'">'.$row['Cust_Name'].','.$row['Cust_City'].'</option>';
}
echo '</select>';
?>
How can I, in the same form, access the address of the particular customer id from database when user selects customer name from this dropdown menu?
I think you mean when you change dropdown, the value is not retained, it obviously won't be because your page is being refresh, you need to GET the value from url and put a selected attribute to have that value selected.
Do it this way:
<?php
$query = "SELECT Cust_id,Cust_Name,Cust_City FROM Customers" ;
$result = mysql_query($query);
//checking if GET variable is set, if yes, get the value
$selected_option = (isset($_GET['product'])) ? $_GET['product'] : '';
//we will store all the dropdown html code in a variable and display it later
$select = "<select id='fullname' onChange=\"window.location='sp_menu.php?product='+this.value\" name='fullname'>";
while($row = mysql_fetch_assoc( $result )) {
//checking if the cust_id matches the GET value,
//if yes, add a selected attribute
$selected = ($selected_option==$row['Cust_id'])?'selected':'';
echo '<option value="'.$row['Cust_id'].'"'. $selected. '>' . $row['Cust_Name'] .' , '.$row['Cust_City']. '</option>';
}
$select .= '</select>';
//display the dropdown
echo $select;
?>

Setting combo box to value dynamically retrieved from database in PHP

I have a task that I need to retrieve data from the database and set it in the Combo Box. Fortunately, I have done it.
Now, I have a Search Button which retrieves the data relevant in these text and combo boxes. My Issue is, After I click Search Button all my combo box and text box selected values become empty. How can I set those same data after clicking Search button ?
My Code Effort is,
<?php
$sql="select cat_id,cat_name from disease_category group by cat_id ";
foreach ($dbo->query($sql) as $row){
if(isset($_REQUEST['cat_name'])&&$_REQUEST['cat_name']==$row[cat_name])
{
echo "<option value=$row[cat_id] selected='selected' >$row[cat_name]</option>";
}
Else
{
echo "<option value=$row[cat_id]>$row[cat_name]</option>";
}
}
?>
My SEARCH button code,
<?php
include 'config.php';
if(isset($_REQUEST['SUBMIT']))
{
$cat=$_REQUEST['cat'];
$subcat=$REQUEST['subcat']
$sel=mysql_query("SELECT * from table_name where cat_id like '$cat%' AND sub_id like '$sub_cat%'AND survier like '$survier%' ")
}
It should be pretty simple. I still don't fully understand what you're trying to do. But if all you want is to dynamically populate an options list based on the results of a SQL query.
<?php
$sql = '
SELECT
*
FROM
`my_table`
';
$query = mysql_query($sql) OR die(mysql_error());
print '<select name="dropdown">';
while ($row = mysql_fetch_assoc($query)) {
print '<option value="'. $row['cat_id'] .'"';
if (
isset($_REQUEST['cat_name']) &&
$_REQUEST['cat_name'] == $row['cat_name']
) { print ' selected="selected"'; }
print '>'. $row['cat_name'] .'</option>';
}
print '</select>';
?>
You should be able to modify the SELECT query to fit your needs, and modify content within the while() loop, as well. That should get you going if I understand what you're trying to do.

Run Submit Button on inital page load

I have a table using the variables from the below drop down menu. When the user selects the option in the drop down the table pulls the information based on the variable tied to the selection. How ever when the page first loads it errors out saying the query is missing the variable from the drop down. If I make a selection from the drop down it refreshes the page and resolves the issue. I need the drop down to initially submit the data or whatever is necessary for the query to get its variable on intial page load.
$selected = 'selected = "selected" ';
$Country =$ID_SOCIEDAD;
echo "<form name='country_list' method='POST' action='http://opben.com/colombia/familias-de-carteras' >";
echo "<select name='Country' tabindex='1' >";
while($row = mysql_fetch_array($result))
{
echo " <option ".($row['Fund_Manager_Company_Code'] == $Country? $selected : '')."value='". $row['Fund_Manager_Company_Code'] ."'>". $row['Fund_Manager_Company_Name'] ."</option>";
}
echo " </select>
<input type='submit' value='Filter' />";
echo " </form>
Here is the sql query for the drop down menu options:
$result = mysql_query("
SELECT
ID_SOCIEDADADM as Fund_Manager_Company_Code,
DES_SOCIEDAD_CORTO as Fund_Manager_Company_Name
FROM dr_lista_rentabilidad_diaria
GROUP BY ID_SOCIEDADADM
")
or die(mysql_error());
Here is the query for the table:
$result = mysql_query("
SELECT
ID_CARTERA as Fund_ID,
DES_CARTERA_CC as Fund_Name,
DES_CARTERACLASE as Class_Name,
DES_CARTERACLASE_ESP as Special_Class_Name,
FORMAT(POR_RENTCARTERA_C1,2) AS Yield_1month
FROM dr_lista_rentabilidad_diaria
WHERE COD_PAIS = $COD_PAIS
AND ID_SOCIEDADADM = $ID_SOCIEDAD
AND `ID_COLUMNA_C1`= $ID_COLUMNA
ORDER BY DES_CARTERA_CC ASC
")
or die(mysql_error());
You didn't post your query, so it is hard to give an appropriate answer. However, my guess is that you have the variable $_POST['Country'] somewhere in that query. So why don't you do this:
$country = $_POST['Country'];
if (!isset($country)) { $country = 'US'; }
$query = 'SELECT * FROM table WHERE country = ' . $country;
EDIT: As BenM (correctly) pointed out, this code snippet is absolutely not save. You should NOT include this in your production code. It was just meant to give you an idea on how to avoid the SQL error you are getting by always providing a valid value for the country.

Categories