Keep selected option in table selected - php

my problem is that i have a page where you can add rows to a table and in the table is a drop down.
For the dropdown it should automatically keep the selected index and the next added row should be the same option selected as the row above.
That works however the row above does not keep the selected option and resets to the first option.
<?php
session_start();
require_once '../../connect/db.php';
include '../../functions/function.php';
if(!isset($_SESSION['row'])){
$_SESSION['row'] = 1;
}
$def = 4;
$pass = 5;
$run = 3;
if(isset($_POST['add'])){
$_SESSION['row']++;
}
if(isset($_POST['reset'])){
$_SESSION['row']=1;
}
?>
<html>
<head>
<title>Insert Plays</title>
<link rel="stylesheet" href="../../style/style.css">
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<div class="navbar">
<a href='home.php'>My Teams</a>
<a class="active" href=''>Insert Plays</a>
<a href='home.php?show=manage'>Manage Teams</a>
<a href='edit_profile.php'>Edit Profile</a>
<a class='log' href='../../index.php'>Logout</a>
</div>
<div class="content">
<form action="" method="post">
<table border="1">
<?php
$row = $_SESSION['row'];
echo $row;
$output = "";
for($i = 0;$i<$row;$i++){
$output .= "<tr>";
if ($i == $_SESSION['row']-1){
echo "Testaaaa";
$test = "playType".($i-1);
switch($_POST[$test]){
case 'pass':
$output .= "<td><select name='playType".$i."'>
<option selected value='pass' name='type'>Pass</option>
<option value='run' name='type'>Run</option>
<option value='def' name='type'>Def</option>
</select></td>";
break;
case 'run':
$output .= "<td><select name='playType".$i."'>
<option value='pass' name='type'>Pass</option>
<option selected value='run' name='type'>Run</option>
<option value='def' name='type'>Def</option>
</select></td>";
break;
case 'def':
$output .= "<td><select name='playType".$i."'>
<option value='pass' name='type'>Pass</option>
<option value='run' name='type'>Run</option>
<option selected value='def' name='type'>Def</option>
</select></td>";
break;
};
}
else{
$output .= "<td><select name='playType".$i."'>
<option value='pass' name='type'>Pass</option>
<option value='run' name='type'>Run</option>
<option value='def' name='type'>Def</option>
</select></td>";
}
$output .= "</tr>";
}
echo "$output";
?>
</table>
<input type="submit" value="Add Row" name="add"><br>
<input type="submit" name="reset" value="Reset">
</form>
</div>
</body>
</html>

Related

A swap button for a currency converter

I have a problem with this code, what happens is that I want to create a swap button to change two selectbox of place, such as the google currency converter and those of the internet, I would greatly appreciate your help if you taught me how to do it, the code I did with php. And an apology if I said something wrong I am a beginner in this world
// Output text
$out = $ans = $txtAmount =
// txtSelectBox1 selection
$selA0 = $selA1 = $selA2 = $selA3 =
// txtSelectBox2 selection
$selB0 = $selB1 = $selB2 = $selB3 = "";
// Check if form was submitted
if(isset($_POST['txtSelectBox1'])) {
// Get post values
$txtSel1 = $_POST['txtSelectBox1'];
$txtSel2 = $_POST['txtSelectBox2'];
$txtAmount = $_POST['txtAmount'];
// Exchange rates
$cur = array("MXN", "USD", "EUR", "JPY");
$php = array("1", "0.050", "0.048", "6.78");
$cad = array("20.12", "1", "0.96", "136.50");
$hkd = array("20.99", "1.04", "1", "142.51");
$jpy = array("0.15", "0.0073", "0.0070", "1");
// Switch statement for conversion
switch ($txtSel1) {
case "php":
$selA0 = ${"selB".$txtSel2} = "selected";
$ans = $txtAmount * floatval($php[$txtSel2]);
$case = 0;
break;
case "cad":
$selA1 = ${"selB".$txtSel2} = "selected";
$ans = $txtAmount * floatval($cad[$txtSel2]);
$case = 1;
break;
case "hkd":
$selA2 = ${"selB".$txtSel2} = "selected";
$ans = $txtAmount * floatval($hkd[$txtSel2]);
$case = 2;
break;
case "jpy":
$selA3 = ${"selB".$txtSel2} = "selected";
$ans = $txtAmount * floatval($jpy[$txtSel2]);
$case = 3;
break;
}
// Display output
$out = '<div class="answer">'.$txtAmount.' '.$cur[$case].' = '.$ans.' '.$cur[$txtSel2].'</div>';
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Conversor de Divisas</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<main>
<div class="container">
<div class="title">
<h1>CONVERSOR</h1>
</div>
<div class="container-wrapper">
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" class="frmSelect" name="frm">
<div class="selectWrapper">
<select class="txtSelectBox" name="txtSelectBox1" id="txtSelectBox1">
<option value="php" <?php echo $selA0; ?>>Peso Mexicano (MXN)</option>
<option value="cad" <?php echo $selA1; ?>>Dolar (USD)</option>
<option value="hkd" <?php echo $selA2; ?>>Euro (EUR)</option>
<option value="jpy" <?php echo $selA3; ?>>Yen Japones (JPY)</option>
</select>
<select class="txtSelectBox" name="txtSelectBox2" id="txtSelectBox2">
<option value="0" <?php echo $selB0; ?>>Peso Mexicano (MXN)</option>
<option value="1" <?php echo $selB1; ?>>Dolar (USD)</option>
<option value="2" <?php echo $selB2; ?>>Euro (EUR)</option>
<option value="3" <?php echo $selB3; ?>>Yen Japones (JPY)</option>
</select>
</div>
<input type="number" class="txtbox" name="txtAmount" id="txtAmount" value="<?php echo $txtAmount; ?>" placeholder="Input Amount" required>
<div class="btnWrapper">
Restaurar
<button type="submit" class="btn btnConvert" name="btnConvert">Convertir</button>
</div>
<?php echo $out; ?>
</form>
</div>
</div>
</main>
</body>
</html>```

Why can't I unselect the last option in multiselect after I save it to a session variable?

I have a multi-select which saves the currently selected options using a session variable. However when I un-select all options, the last selected option stays. How do I fix this? Here is my code:
<!DOCTYPE html>
<?php
session_start();
if(isset($_POST['occupation']))
$_SESSION['occupation'] = $_POST['occupation'];
?>
<html>
<head>
</head>
<body>
<form method="post" action="">
<h2>Industy</h2>
<select name="occupation[]" multiple >
<?php
$occ = array("Accounting", "Education", "Healthcare", "Information Technology", "Retail", "Sales");
$len = count($occ);
for($i = 0; $i<$len; $i++ )
{
if(in_array($occ[$i], $_SESSION['occupation']))
echo '<option value="' . $occ[$i] . '" selected>' . $occ[$i] .'</option>';
else
echo '<option value="' . $occ[$i] . '" >' . $occ[$i] .'</option>';
}
?>
</select>
<br/><br/>
<button type="submit" value="Search" class="my-button" name="search_button" >Search</button>
</form>
</body>
</html>
Just add to your code that if you submitted without any value, just overwrite the session array empty.
Here's the idea:
<?php
session_start();
$occ = array("Accounting", "Education", "Healthcare", "Information Technology", "Retail", "Sales");
if (empty($_SESSION['occupation'])) { // initialize
$_SESSION['occupation'] = array();
}
if(isset($_POST['search_button'])) { // if submitted
// set session occupation else just set empty
$_SESSION['occupation'] = !empty($_POST['occupation']) ? $_POST['occupation'] : array();
}
?>
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<form method="post" action="">
<h2>Industy</h2>
<select name="occupation[]" multiple>
<?php foreach ($occ as $o) { ?>
<option value="<?php echo $o; ?>" <?php echo in_array($o, $_SESSION['occupation']) ? 'selected' : ''; ?>>
<?php echo $o; ?>
</option>
<?php } ?>
</select>
<br/><br/>
<button type="submit" value="Search" class="my-button" name="search_button" >Search</button>
</form>
</body>
</html>

For loop inserts only 1 MySQL record

I have been working on a form that allows entering a menu item for a cafe establishment, alongside its ingredients (arrays of data). Unfortunately, a problem came up as it only executes 1 query even though 2 or more ingredients were entered in the form (dynamic, jQuery).
Here is the PHP code:
<?php
include("session.php");
if (isset($_POST['submit'])) {
$productname = $_POST['product_name'];
$categoryID = $_POST['categoryID'];
$price = $_POST['srp'];
// ingredients
$ingredients = $_POST['ingredients'];
$qty = $_POST['qty'];
$measure = $_POST['measure'];
if (!empty($productname) && !empty($categoryID) && !empty($price) && !empty($ingredients) && !empty($qty) && !empty($measure)) {
for ($i=0; $i < count($ingredients); $i++) {
if ($ingredients[$i] != "" && $qty[$i] != "" && $measure[$i] != "") {
mysqli_query($db, "insert into individual_ingredients values ('', '$productname', '{$ingredients[$i]}', '{$qty[$i]}', '{$measure[$i]}')");
}
}
mysqli_query($db, "insert into end_products values ('', '$productname', '$price', '', '$categoryID')");
mysqli_query($db, "insert into audit_trail values ('', now(), '{$_SESSION['login_user']}', 'New end product added')");
header("location: end_products.php");
} else {
echo '<font color="red">'."Incomplete data entered".'</font>';
}
}
?>
And here is the HTML form and JQuery:
<html>
<head>
<title><?php echo $login_session; ?> | New End Product Record</title>
<link rel="stylesheet" href="css/main.css" type="text/css">
<link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet">
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<!-- Bootstrap js library -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
//add more fields group
$(".addMore").click(function(){
var fieldHTML = '<div class="form-group fieldGroup">'+$(".fieldGroupCopy").html()+'</div>';
$('body').find('.fieldGroup:last').after(fieldHTML);
});
//remove fields group
$("body").on("click",".remove",function(){
$(this).parents(".fieldGroup").remove();
});
});
</script>
</head>
<body>
HTML form:
<table style="margin: 5% -1% 0 -10%; font-size: 0.9em">
<tr>
<form action="new_end_product_record.php" method="post">
<td>Name</td>
<td><input type="text" name="product_name"></td>
<td>Raw Material/s Used</td>
<td>
<div class="fieldGroup">
<select name="ingredients[]">
<option value="">Ingredient</option>
<?php
$items_sql = "select name from raw_materials where status='Active'";
$get_items = mysqli_query($db, $items_sql);
while ($option = mysqli_fetch_assoc($get_items)) { ?>
<option value="<?php echo $option['name']; ?>"><?php echo $option['name']; ?></option>
<?php } ?>
</select>
<input type="text" name="qty[]" placeholder="Quantity" style="width:60px">
<select name="measure[]">
<option value="">Measure Unit</option>
<?php
$get_units = "select * from raw_material_measures";
$units = mysqli_query($db, $get_units);
while ($unit = mysqli_fetch_assoc($units)) {
?>
<option value="<?php echo $unit['full_name']; ?>"><?php echo $unit['full_name']; ?></option>
<?php } ?>
</select>
ADD
<br /><br />
</div>
<!-- second set -->
<div class="fieldGroupCopy" style="display: none;">
<div class="input-group">
<select name="ingredients[]">
<option value="">Ingredient</option>
<?php
$items_sql = "select name from raw_materials where status='Active'";
$get_items = mysqli_query($db, $items_sql);
while ($option = mysqli_fetch_assoc($get_items)) { ?>
<option value="<?php echo $option['name']; ?>"><?php echo $option['name']; ?></option>
<?php } ?>
</select>
<input type="text" name="qty[]" placeholder="Quantity" style="width:60px">
<select name="measure[]">
<option value="">Measure Unit</option>
<?php
$get_units = "select * from raw_material_measures";
$units = mysqli_query($db, $get_units);
while ($unit = mysqli_fetch_assoc($units)) {
?>
<option value="<?php echo $unit['full_name']; ?>"><?php echo $unit['full_name']; ?></option>
<?php } ?>
</select>
REMOVE
<br /><br />
</div>
</div>
</td>
</tr>
<tr>
<td>SRP</td>
<td><input type="text" name="srp"></td>
</tr>
<tr>
<td>Category</td>
<td>
<select name="categoryID">
<option value="">Select category...</option>
<!--list all categories in the database-->
<?php
$cat_query = "select category_ID, name from end_products_categories";
$get_cats = mysqli_query($db, $cat_query);
while ($option = mysqli_fetch_assoc($get_cats)) { ?>
<option value="<?php echo $option['category_ID']; ?>"><?php echo $option['name']?></option>
<?php } ?>
</select>
</td>
<!-- <td>Expiration</td>
<td><input type="date"></input></td> -->
</tr>
</table><br>
<input type="submit" class="button" name="submit" value="ADD RECORD">
<input type="reset" value="ERASE ALL">
</div></form>
</div>
</body>
</html>
Is there a problem with the loop or with the HTML form that prevents the second to the last set of values from being inserted? Any help would be appreciated.

Get text of select box in php page

I have select box in PHP and want text selected item of that:
<form action="" method="get" target="" dir="rtl" class="w3-container">
<?php
echo " <select id='p1' name='p1' >";
echo "<option value='*'>Choose person</option>";
sql code
$result2 = mysql_query($query2,$con);
while($row2 = mysql_fetch_array($result2))
{
$row2['name'];
echo "<option value='".$row2['id']."'>".$row2['name']."</option>";
}
echo " </select>";
mysql_close($con);
?>
<input class="w3-btn w3-hover-yellow" name="" type="submit" value="جستجو">
</form>
<?php
if(isset($_GET['p1']) and $_GET['p1'] != "*")
{
if ($name_insert=trim($_GET["p1"]))
{
if ($strWhere == ""){
$strWhere .= "name_insert='".trim($name_insert)."' ";
$getPage .= "&name_insert=".($name_insert);}
else{
$strWhere .= " and name_insert='".trim($name_insert)."' ";
$getPage .= "&name_insert=".($name_insert);}
}
}
?>
I want code that get text of select box in $name_insert. This code gets value of that.
You can use javascript and save selected option text in a hidden field.
Example
<form action="" method="POST">
<select id="test" onchange="document.getElementById('text_content').value=this.options[this.selectedIndex].text">
<option value="1">Test One</option>
<option value="2">Test Two</option>
</select>
<input type="hidden" name="test_text" id="text_content" value="" />
</form>
PHP
$getOptionText = $_POST['test_text'];
Replace your code with this code
<form action="" method="get" target="" dir="rtl" class="w3-container">
<select id='p1' name='p1' onchange="document.getElementById('text_content').value=this.options[this.selectedIndex].text">
<option value='*'>Choose person</option>
<?php
$result2 = mysql_query($query2,$con);
while($row2 = mysql_fetch_array($result2))
{
echo "<option value='".$row2['id']."'>".$row2['name']."</option>";
}
mysql_close($con);
?>
</select>
<input type="hidden" name="test_text" id="text_content" value="" />
<input class="w3-btn w3-hover-yellow" name="" type="submit" value="جستجو">
</form>
<?php
if(isset($_GET['p1']) and $_GET['p1'] != "*")
{
$getValueOfText = $_GET['test_text'];
echo $getValueOfText;
if ($name_insert=trim($_GET["p1"]))
{
if ($strWhere == ""){
$strWhere .= "name_insert='".trim($name_insert)."' ";
$getPage .= "&name_insert=".($name_insert);}
else{
$strWhere .= " and name_insert='".trim($name_insert)."' ";
$getPage .= "&name_insert=".($name_insert);}
}
}
?>

dropdown selected item not printing

I am trying to print the dropdown selected item. I have well displayed the dropdwon list menu. but when i select an option it doesn't print the option. i have tried in many ways. But not yet got! Please help me, this is my following code.
<form name="choose" method="get" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<?php
$query="SELECT id_cat,name FROM `fs01_metier_cat` ORDER BY `fs01_metier_cat`.`id_cat`";
$result = mysql_query($query);
?>
<?php
echo "<select name=category></option>";
while($nt=mysql_fetch_array($result)) {
echo "<option value='".$nt['name']."'>".$nt['name']."</option>";
}
echo "</select>";
?>
<input type="submit" name="submit" value="save category" />
</form>
<?php
if($_GET){
echo 'The year selected is'.$_GET['category'];
}
?>
You have issues in your code, try this one instead :
<form name="choose" method="get" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<?php
$query="SELECT id_cat,name FROM `fs01_metier_cat` ORDER BY `fs01_metier_cat`.`id_cat`";
$result = mysql_query($query);
?>
<select name=category>
<?php
while($nt=mysql_fetch_array($result)) {
echo "<option value='".$nt['name']."'>".$nt['name']."</option>";
}
?>
</select>
<input type="submit" name="submit" value="save category" />
</form>
<?php
if($_GET){
echo 'The year selected is'.$_GET['category'];
}
?>
$_GET['category']
should be
$_POST['category']
Example for javascript:
<html>
<head>
<script type="text/javascript">
window.onload = function() {
var eSelect = document.getElementById('cat');
eSelect.onchange = function() {
document.getElementById("displaytext").innerHTML = "Selected Value: "+this.value;
document.getElementById("displaytext").style.display= 'block';
}
}
</script>
</head>
<body>
<select id="cat" name="cat">
<option value="x">X</option>
<option value="y">Y</option>
<option value="other">Other</option>
</select>
<div id="displaytext" style="display: none;" ></div>
</body>
</html>
​

Categories