For loop inserts only 1 MySQL record - php

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.

Related

Make AJAX on add and remove items to avoid reload

I have 3 php files in doing addition and deletion of medicine details. medicines detail are used to order drugs for each patient who comes for treatment. In order not to be a hassle, how do I prevent my application from needing to be reloaded with AJAX? The 3 files are: services.php , insertDetailMedicines.php and deleteDetail.php .
services.php
$data = mysqli_query($conn, "SELECT MAX(id_service) AS ids FROM tbl_services");
$final_data = mysqli_fetch_array($data);
$id1 = $final_data['ids'];
$id2 = substr($id1,3,3); //MR for Medical Record
$id3 = $id2 + 1;
$id4 = 'MR'.sprintf('%03s' , $id3); // <-- Auto generating unique id
<form method="POST" action="services.php">
<input type="hidden" name="id_medical_record" value="<?php echo $id4 ?>">
<select name="medicineName" id="medicineName" required>
<option value="">- Choose -</option>
<?php
$medicines = mysqli_query($conn, "SELECT * FROM tbl_medicines ORDER BY id_medicines ASC");
$m = mysqli_fetch_array($medicines);
while($m = mysqli_fetch_array($medicines)){ ?>
<option value="<?php echo $m['id_medicine'] ?>">
<?php echo $m['medicine_name'] ?>
</option>
<?php } ?>
</select>
<input type="text" name="qty_medicines" id="qty_medicines" value="1" required />
<button type="submit" name="add" style="cursor: pointer">ADD</button>
</form>
<table> <!--this is to display the drugs that have been added-->
<?php
$show_details = mysqli_query($conn, "SELECT * FROM tbl_detail_medicines LEFT JOIN tbl_medicines USING (id_medicine)");
$num = 1;
if(mysqli_num_rows($show_details) > 0)
{
while ($detail = mysqli_fetch_array($show_details))
{
?>
<tr>
<td>
<?php echo $num++.'.'; ?>
</td>
<td>
<?php echo $detail['medicine_name'] ?>
</td>
<td>
<?php echo $detail['qty'] ?>
</td>
<td>
<a href="deleteDetail.php?delete=<?php echo $detail['id'] ?>">
<b> X </b>
</a>
</td>
</tr>
<?php
}}
?>
</table>
insertDetailMedicines.php
<?php
if (isset($_POST['add'])) {
$idMR = $_POST['id_medical_record'];
$medicineName = $_POST['medicineName'];
$qty_medicines = $_POST['qty_medicines'];
$insert_detail = "insert into tbl_detail_medicines (id,id_service,id_medicine,qty)
VALUES
(null,'$idMR','$medicineName','$qty_medicines')";
if (mysqli_query($conn,$insert_detail)) {
//echo "inserting success!";
}
}
?>
deleteDetail.php
<?php
require 'koneksi.php';
if(isset($_GET['delete'])){$delete = mysqli_query($conn, "DELETE FROM tbl_detail_medicines WHERE id = '".$_GET['delete']."' ");
header('location:services.php');
}
?>
apppearance

Request Dropdown list

I have a dropdown list with 5 elements (Volleyball, Handball, Rugby, Basketball, Autres)
I wish for example to select the element "Rugby" in my form, then confirm.
My problem is when I wish to change my old choice in my form (edit); the element "Rugby" is not the element which has been save previously.
By default I always have the element "VolleyBall".
[![<td>Type de Club:</td><td>
<select name="type_club" style="width:144px">
<option>Volley-Ball</option>
<option>Hand-Ball</option>
<option>Rugby</option>
<option>Basket-Ball</option>
<option>Autres</option>
</select>][1]][1]
[1]: https://i.stack.imgur.com/xQ83B.png
Here is my code.
<?php
// including the database connection file
include_once("config_bd.php");
if(isset($_POST['update']))
{
$pk_club = mysqli_real_escape_string($mysqli, $_POST['pk_club']);
$nom_club = mysqli_real_escape_string($mysqli, $_POST['nom_club']);
$type_club = mysqli_real_escape_string($mysqli, $_POST['type_club']);
// checking empty fields
if(empty($nom_club) || empty($type_club)) {
if(empty($nom_club)) {
echo "<font color='red'>Le nom du club est vide.</font><br/>";
}
if(empty($type_club)) {
echo "<font color='red'>Le type du club est vide.</font><br/>";
}
} else {
//updating the table
$result = mysqli_query($mysqli, "UPDATE clubs SET nom_club='$nom_club',type_club='$type_club' WHERE pk_club=$pk_club");
//redirectig to the display page. In our case, it is index.php
header("Location: vue_club.php");
}
}
//getting id from url
$pk_club = $_GET['pk_club'];
//selecting data associated with this particular id
$result = mysqli_query($mysqli, "SELECT * FROM clubs WHERE pk_club=$pk_club");
while($res = mysqli_fetch_array($result))
{
$nom_club = $res['nom_club'];
$type_club = $res['type_club'];
}
?>
<html>
<head>
</head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Palais des Sports</title>
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<link rel="stylesheet" type="text/css" href="style/style1.css">
<body>
<div class="bandeau-bleu">
<h2>Palais des Sports</h2>
<i class="material-icons"></i>
<i class="material-icons"></i>
</div>
<div class="form_encodage">
<h3>Cliquez ici pour afficher les enregistrements</h3>
<br />
<h4> Editer un enregistrement</h4><br />
<form name="form1" method="post" action="edit_club.php">
<table border="0">
<tr>
<td>Nom du Club:</td>
<td><input type="text" name="nom_club" value="<?php echo $nom_club;?>"></td>
</tr>
<tr>
<td>Type de Club:</td><td>
<select name="type_club" style="width:144px">
<option>Volley-Ball</option>
<option>Hand-Ball</option>
<option>Rugby</option>
<option>Basket-Ball</option>
<option>Autres</option>
</select>
</td></tr>
<td><input type="submit" name="update" class="bouton_bleu" value="Update"></td>
<td><input type="hidden" name="pk_club" value=<?php echo $_GET['pk_club'];?>></td>
</tr>
</table>
</form>
</div>
</body>
</html>
You can use selected property with options.
Below is updated code for dropdown you have put thin td.
Try this:
<td>Type de Club:</td><td>
<select name="type_club" style="width:144px">
<option <?php if(isset($type_club) and $type_club=='Volley-Ball'){ echo 'selected'; }?>>Volley-Ball</option>
<option <?php if(isset($type_club) and $type_club=='Hand-Ball'){ echo 'selected'; }?>>Hand-Ball</option>
<option <?php if(isset($type_club) and $type_club=='Rugby'){ echo 'selected'; }?>>Rugby</option>
<option <?php if(isset($type_club) and $type_club=='Basket-Ball'){ echo 'selected'; }?>>Basket-Ball</option>
<option <?php if(isset($type_club) and $type_club=='Autres'){ echo 'selected'; }?>>Autres</option>
</select>
</td>
Complete updated code:
<?php
// including the database connection file
include_once("config_bd.php");
if(isset($_POST['update']))
{
$pk_club = mysqli_real_escape_string($mysqli, $_POST['pk_club']);
$nom_club = mysqli_real_escape_string($mysqli, $_POST['nom_club']);
$type_club = mysqli_real_escape_string($mysqli, $_POST['type_club']);
// checking empty fields
if(empty($nom_club) || empty($type_club)) {
if(empty($nom_club)) {
echo "<font color='red'>Le nom du club est vide.</font><br/>";
}
if(empty($type_club)) {
echo "<font color='red'>Le type du club est vide.</font><br/>";
}
} else {
//updating the table
$result = mysqli_query($mysqli, "UPDATE clubs SET nom_club='$nom_club',type_club='$type_club' WHERE pk_club=$pk_club");
//redirectig to the display page. In our case, it is index.php
header("Location: vue_club.php");
}
}
//getting id from url
$pk_club = $_GET['pk_club'];
//selecting data associated with this particular id
$result = mysqli_query($mysqli, "SELECT * FROM clubs WHERE pk_club=$pk_club");
while($res = mysqli_fetch_array($result))
{
$nom_club = $res['nom_club'];
$type_club = $res['type_club'];
}
?>
<html>
<head>
</head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Palais des Sports</title>
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<link rel="stylesheet" type="text/css" href="style/style1.css">
<body>
<div class="bandeau-bleu">
<h2>Palais des Sports</h2>
<i class="material-icons"></i>
<i class="material-icons"></i>
</div>
<div class="form_encodage">
<h3>Cliquez ici pour afficher les enregistrements</h3>
<br />
<h4> Editer un enregistrement</h4><br />
<form name="form1" method="post" action="edit_club.php">
<table border="0">
<tr>
<td>Nom du Club:</td>
<td><input type="text" name="nom_club" value="<?php echo $nom_club;?>"></td>
</tr>
<tr>
<td>Type de Club:</td><td>
<select name="type_club" style="width:144px">
<option <?php if(isset($type_club) and $type_club=='Volley-Ball'){ echo 'selected'; } ?>>Volley-Ball</option>
<option <?php if(isset($type_club) and $type_club=='Hand-Ball'){ echo 'selected'; } ?>>Hand-Ball</option>
<option <?php if(isset($type_club) and $type_club=='Rugby'){ echo 'selected'; } ?>>Rugby</option>
<option <?php if(isset($type_club) and $type_club=='Basket-Ball'){ echo 'selected'; } ?>>Basket-Ball</option>
<option <?php if(isset($type_club) and $type_club=='Autres'){ echo 'selected'; }?>>Autres</option>
</select>
</td></tr>
<td><input type="submit" name="update" class="bouton_bleu" value="Update"></td>
<td><input type="hidden" name="pk_club" value=<?php echo $_GET['pk_club'];?>></td>
</tr>
</table>
</form>
</div>
</body>
</html>
You will need to query your database before loading your select form to get the previous save then build your list
$sqla= "SELECT * FROM `save_table` WHERE `id` = $id ";
$result = $conn->query($sqla);
if ($result->num_rows > 0) {
$save = $row['save'];
$select= ('<td>Type de Club:</td><td>
<select name="type_club" style="width:144px">
<option>');
$select.='$save';
$select.='</option> <option>Volley-Ball</option>
<option>Hand-Ball</option>
<option>Rugby</option>
<option>Basket-Ball</option>
<option>Autres</option>
</select>';
echo $select;
You can also use if statements to remove the second $save variable from the list before you build it so there is no repeat option in the list.

Unit Converter PHP

I am struggling to get my PHP unit converter to work.
I am trying to get multiple converters going but cant seem to get it working.
It'd be great if someone could show me where I'm going wrong and help me get it going. :)
<?php
if($_POST){
$fahrenheit = $_POST['fahrenheit'];
$celsius = ($fahrenheit - 32)*5/9;
}
if($_POST){
$celsius = $_POST['celcius'];
$fahrenheit = ($celcius - 32)*5/9;
}
?>
<form action="" method="post">
Fahrenheit: <input type="text" name="fahrenheit" /><br />
<?php
if(isset($celsius)){
echo "Celsius = ".$celsius;
}
?>
</form>
<?php
function fahrenheit_to_celsius($given_value)
{
$celsius=5/9*($given_value-32);
return $celsius ;
}
function celsius_to_fahrenheit($given_value)
{
$fahrenheit=$given_value*9/5+32;
return $fahrenheit ;
}
function inches_to_centimeter($given_value)
{
$centimeter=$given_value/2.54;
return $centimeter ;
}
function centimeter_to_inches($given_value)
{
$inches=$given_value*2.54
}
?>
<html>
<head>
<title>Temp. Conv.</title>
</head>
<body>
<form action="" method="post">
<table>
<!-- FAHRENHEIGHT & CELCIUS V -->
<tr>
<td>
<select name="first_temp_type_name">
<option value="fahrenheit">Fahrenheit</option>
<option value="celsius">Celsius</option>
</select>
</td>
</tr>
<tr>
<td>
<input type="text" name="given_value">
</td>
</tr>
<tr>
<td>
<select name="second_temp_type_name">
<option value="fahrenheit">Fahrenheit</option>
<option value="celsius">Celsius</option>
</select>
</td>
</tr>
<tr>
<td>
<input type="submit" name="btn" value="Convert">
</td>
</tr>
<!--FAHRENHEIGHT & CELCIUS ^ -->
<!-- CENTEMETERS & INCHES -->
<tr>
<td>
<select name="first_length_type_name">
<option value="centimeter">centimeter</option>
<option value="inches">Inches</option>
</select>
</td>
</tr>
<tr>
<td>
<input type="text" name="given_value">
</td>
</tr>
<tr>
<td>
<select name="second_length_type_name">
<option value="centimeter">centimeter</option>
<option value="inches">Inches</option>
</select>
</td>
</tr>
<tr>
<td>
<input type="text" name="given_value">
</td>
</tr>
<!--CENTEMETERS & INCHES ^-->
<tr>
<td>
<?php
if(isset($_POST['btn']))
{
$first_temp_type_name=$_POST['first_temp_type_name'];
$second_temp_type_name=$_POST['second_temp_type_name'];
$given_value=$_POST['given_value'];
if($first_temp_type_name=='fahrenheit')
{
$celsious=fahrenheit_to_celsius($given_value);
echo "Fahrenheit $given_value = $celsious Celsious";
}
if($first_temp_type_name=='celsius')
{
$fahrenheit=celsius_to_fahrenheit($given_value);
echo "Celsious $given_value = $fahrenheit Fahrenheit";
}
}
if(isset($_POST['btn']))
{
$first_length_type_name=$_POST['first_length_type_name'];
$second_length_type_name=$_POST['second_length_type_name'];
$given_value=$_POST['given_value'];
if($first_length_type_name=='centimeter')
{
$centimeter=centimeter_to_inches($given_value);
echo "Centimeter $given_value = $inches Inches";
}
if($first_length_type_name=='inches')
{
$centimeter=inches_to_centimeter($given_value);
echo "Inches $given_value = $centimeter centimeter";
}
}
?>
</td>
</tr>
</table>
</form>
</body>
</html>
I know there is a lot going on, my apologies.
Any help is greatly appreciated :)
Hi please use the following code.
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
$convertedTemperature = 0;
/* The condition is entered when the request is of POST type. */
if($_SERVER['REQUEST_METHOD'] == 'POST'){
$temperature = $_POST['temperature'];
$fromConvertionUnit = $_POST['fromConvertionUnit'];
$toConvertionUnit = $_POST['toConvertionUnit'];
/* if the temperature conversion are of same unit then no need for conversion */
if($fromConvertionUnit == $toConvertionUnit){
$convertedTemperature = $temperature;
}else if($fromConvertionUnit == 'fahrenheit' && $toConvertionUnit == 'celcius') {
/* formula to convert Fahrenheit to Celcius */
$convertedTemperature = ($temperature - 32) * 0.5556;
}else if($fromConvertionUnit == 'celcius' && $toConvertionUnit == 'fahrenheit') {
/* formula to convert Celcius to Fahrenheit */
$convertedTemperature = ($temperature * 1.8) + 32;
}
}
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Temperature Converter</title>
</head>
<body>
<form action="<?php echo $_SERVER['PHP_SELF'] ?>" method="post">
<div>
<!-- If the temperature value has be submitted and has data then it will prefilled -->
<label for="temperature">Temperature</label> <br/>
<input type="number" name="temperature" id="temperature" value="<?php echo (!empty($temperature)) ? $temperature : '' ?>">
</div>
<div>
<label for="fromConvertionUnit">Select From Convertion Unit</label><br/>
<select name="fromConvertionUnit" id="fromConvertionUnit">
<option value="fahrenheit">Fahrenheit</option>
<option value="celcius">Celcius</option>
</select>
</div>
<div>
<label for="toConvertionUnit">Select To Convertion Unit</label><br/>
<select name="toConvertionUnit" id="toConvertionUnit">
<option value="fahrenheit">Fahrenheit</option>
<option value="celcius">Celcius</option>
</select>
</div>
<!-- Once the page is submitted and conversion is done the respective values will be added in the following section -->
<div>
Converted Temperature <b> <?php echo (!empty($temperature)) ? $temperature : '--' ?></b> Value From <b><?php echo (!empty($fromConvertionUnit)) ? $fromConvertionUnit : '--' ?></b> TO <b><?php echo (!empty($toConvertionUnit)) ? $toConvertionUnit : '--' ?></b> is <b><?php echo (!empty($convertedTemperature)) ? $convertedTemperature : '--' ?><b/>
<label for="converted_value">Converted Value</label><br/>
<input type="number" value="<?php echo (!empty($convertedTemperature)) ? $convertedTemperature : '0' ?>">
</div>
<div>
<input type="submit" value="Convert">
</div>
</form>
</body>
</html>
If you want to make a converter, all you need is one input - and a dropdown between what you wish to convert to. Then use a switch in PHP when the form was submitted to check what function you wish to use.
Your current issue is that you overwrite a lot of values, and that you don't check for the right buttons. This is also over-complicating it.
You can further develop this converter by making sure that the input is an actual number - by using filter_var() with a flag that's suitable for your need. You can either validate it or sanitize it, see FILTER_SANITIZE vs FILTER VALIDATE, whats the difference - and which to use?.
<?php
if (isset($_POST['submit'])) {
switch ($_POST['convert']) {
case "cm-in":
$result = centimeter_to_inches($_POST['value']);
$old_unit = 'cm';
$new_unit = ' inches';
break;
case "in-cm":
$result = inches_to_centimeter($_POST['value']);
$old_unit = ' inches';
$new_unit = 'cm';
break;
case "f-c":
$result = fahrenheit_to_celsius($_POST['value']);
$old_unit = ' Farenheit';
$new_unit = ' Celcius';
break;
case "c-f":
$result = celsius_to_fahrenheit($_POST['value']);
$old_unit = ' Celcius';
$new_unit = ' Farenheit';
break;
}
}
function fahrenheit_to_celsius($given_value) {
return 5/9*($given_value-32);
}
function celsius_to_fahrenheit($given_value) {
return $given_value*9/5+32;
}
function inches_to_centimeter($given_value) {
return $given_value/2.54;
}
function centimeter_to_inches($given_value) {
return $given_value*2.54;
}
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Conversions</title>
</head>
<body>
<form method="post">
Convert <input type="text" name="value" /><br />
<select name="convert">
<option value="">--Select one--</option>
<optgroup label="Units of Length">
<option value="cm-in">Centimeter to inches</option>
<option value="in-cm">Inches to centimeter</option>
</optgroup>
<optgroup label="Units of Temperature">
<option value="f-c">Farenheit to Celcius</option>
<option value="c-f">Celcius to Farenheit</option>
</optgroup>
</select>
<input type="submit" name="submit" value="Convert" />
</form>
<?php
if (!empty($result))
echo '<p>'.$_POST['value'].$old_unit.' equals '.$result.$new_unit.'</p>';
?>
</body>
</html>

Not able to update 2 items using php and mysqli

I have a table where I want to update data in 2 rows.
Heres my code:
<?php
include("includes/conn.php");
session_start();
if(!isset($_SESSION['username']))
{
header('Location: login.php');
}
else{
?>
<?php
$page_title = 'Update Order';
include("includes/header.inc.php");
?>
<?php if( $_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['update-order']) ){
if( !empty($_POST['productname']) && !empty($_POST['quantity']) && !empty($_POST['price']) && !empty($_POST['amount']) ){
$total = 0;
$pid = mysqli_real_escape_string($db,$_POST['pid']);
$advance = mysqli_real_escape_string($db,$_POST['advance_paid']);
$dod = mysqli_real_escape_string($db,$_POST['dod']);
$dod = date('Y-m-d', strtotime($dod));
$mop = mysqli_real_escape_string($db,$_POST['mop']);
for($i = 0; $i<count($_POST['productname']); $i++)
{
$total = $total + $_POST['amount'][$i];
$query = "UPDATE `invoice` SET product_name = (select name from item where id = '{$_POST['productname'][$i]}'), quantity = '{$_POST['quantity'][$i]}', price = '{$_POST['price'][$i]}', discount = '{$_POST['discount'][$i]}', amount = '{$_POST['amount'][$i]}', dod = '{$dod}', added_by = '{$_SESSION['id']}' WHERE id = '{$pid}' ";
mysqli_query($db, $query);
$update_stock = "UPDATE `item` SET added_by = '{$_SESSION['id']}', total_stock = total_stock + '{$_SESSION['quant']}' - '{$_POST['quantity'][$i]}' WHERE id = '{$_POST['productname'][$i]}'";
mysqli_query($db, $update_stock);
}
$query_orders = "UPDATE `orders` SET amount = '{$total}', dod = '{$dod}', mop = '{$mop}', advance = '{$advance}', added_by = '{$_SESSION['id']}' WHERE order_id = '{$_POST['orderid']}' ";
mysqli_query($db, $query_orders);
}
}
?>
<div id="alteration-form">
<div style="width: 90%; margin: 0 auto;">
<form method="GET" action="">
<label for="update_orderno" >Order NO.</label>
<input type="text" name="orderno" class="input-field" id="update_orderno" />
<input type="submit" name="find-order" value="Search Order" class="btn-all-submit" id="btn-order" />
</form>
</div>
</div>
<?php if( $_SERVER["REQUEST_METHOD"] == "GET" ){ ?>
<?php
if( !empty($_GET['orderno']) ){
$orderno = $_GET['orderno'];
$sql_cust = "SELECT cust_id FROM `orders` where order_id = '$orderno' ";
$result_cust = mysqli_query($db, $sql_cust);
if( mysqli_num_rows($result_cust) > 0 ){
while( $row_cust = mysqli_fetch_array($result_cust, MYSQLI_ASSOC) ){
$cust_id = $row_cust['cust_id'];
}
$sql_name = "SELECT * FROM `users` WHERE id = '$cust_id' ";
$result_name = mysqli_query($db, $sql_name);
if( mysqli_num_rows($result_name) > 0 ){
while( $row_name = mysqli_fetch_array($result_name, MYSQLI_ASSOC) ){
$name = $row_name['name'];
$phone = $row_name['phone'];
$address = $row_name['address'];
$city = $row_name['city'];
$state = $row_name['state'];
}
}
}
?>
<div class="result-table-div">
<div class="divRow">
<div class="divCell" ><strong>Name:</strong></div>
<div class="divCell" ><?php echo $name; ?></div>
<?php if(!empty($phone)){ ?>
<div class="divCell" ><strong>Phone:</strong></div>
<div class="divCell" ><?php echo $phone; ?></div>
<?php } ?>
</div>
<div class="divRow">
<?php if(!empty($address)){ ?>
<div class="divCell" ><strong>Address:</strong></div>
<div class="divCell" ><?php echo $address; ?></div>
<?php } ?>
<?php if(!empty($city)){ ?>
<div class="divCell" ><strong>City:</strong></div>
<div class="divCell" ><?php echo $city; ?></div>
<?php } ?>
</div>
<div class="divRow">
<?php if(!empty($state)){ ?>
<div class="divCell" ><strong>State:</strong></div>
<div class="divCell" ><?php echo $state; ?></div>
<?php } ?>
</div>
</div>
<div class="result-table-div">
<form method="POST" action="">
<div class="divRow">
<div class="divCell" ><strong>Date of Delivery:</strong></div>
<div class="divCell" ><input type="text" name="dod" id="dod" value="<?php echo date("m/d/Y"); ?>"/></div>
<div class="divCell" ><strong>Mode of Payment:</strong></div>
<div class="divCell" >
<select name="mop">
<option value="cash">Cash</option>
<option value="card/cheque/online banking">Card/Cheque/Online Banking</option>
</select>
</div>
</div>
<table id="invoice-table">
<thead>
<tr>
<th>S No.</th>
<th>Item</th>
<th>Quantity</th>
<th>Price</th>
<th>Discount</th>
<th>Amount</th>
</tr>
</thead>
<tbody>
<?php
$sql = "SELECT * FROM invoice where order_id = '$orderno' ";
$result = mysqli_query($db, $sql);
if( mysqli_num_rows($result) > 0 ){
$count = 1;
while( $row = mysqli_fetch_array($result,MYSQLI_ASSOC) ){
$id = $row['id'];
$product_name = $row['product_name'];
$quantity = $row['quantity'];
$price = $row['price'];
$discount = $row['discount'];
$amount = $row['amount'];
$_SESSION['cust_id'] = $row['cust_id'];
$_SESSION['quant'] = $quantity;
?>
<tr>
<input type="hidden" name="pid" value="<?php echo $id; ?>" />
<td><?php echo $count++; ?></td>
<!--<td><input type="text" name="productname[]" value="?php echo $product_name ?>"></td>-->
<td>
<select name="productname[]">
<option value="1" <?php if( isset($product_name) && strtolower($product_name) == "bags" ) echo "selected"; ?> >Bags</option>
<option value="2" <?php if( isset($product_name) && strtolower($product_name) == "shoes" ) echo "selected"; ?> >Shoes</option>
<option value="3" <?php if( isset($product_name) && strtolower($product_name) == "suit" ) echo "selected"; ?> >Suit</option>
<option value="4" <?php if( isset($product_name) && strtolower($product_name) == "belts" ) echo "selected"; ?> >Belts</option>
<option value="5" <?php if( isset($product_name) && strtolower($product_name) == "t-shirts" ) echo "selected"; ?> >T-shirts</option>
<option value="6" <?php if( isset($product_name) && strtolower($product_name) == "others" ) echo "selected"; ?> >Others</option>
</select>
</td>
<td><input type="text" class="quantity" name="quantity[]" value="<?php echo $quantity ?>"></td>
<td><input type="text" class="price" name="price[]" value="<?php echo $price ?>"></td>
<td><input type="text" class="discount" name="discount[]" value="<?php echo $discount ?>"></td>
<td><input type="text" class="amount" name="amount[]" value="<?php echo $amount ?>"></td>
</tr>
<?php
}
?>
<input type="hidden" name="orderid" value="<?php echo $orderno; ?>">
<?php
}
?>
</tbody>
</table>
<p style="text-align: center;">Advanced Paid: <input type="text" name="advance_paid" /></p>
<div class="btn-div">
<input type="submit" class="btn-all-submit" name="update-order" value="Update Order">
</div>
</form>
</div>
<?php } } ?>
<script>
$('body').delegate('.quantity,.price,.discount','keyup',function()
{
var tr=$(this).parent().parent();
var qty=tr.find('.quantity').val();
var price=tr.find('.price').val();
var dis=tr.find('.discount').val();
var amt =(qty * price)-(qty * price *dis)/100;
tr.find('.amount').val(amt);
});
</script>
<?php include("includes/footer.inc.php"); ?>
<?php } ?>
I am using for loop to update the data but if I have 2 items to update, it is only updating second item and not the first one. Can someone please help me with this.
Problem occurs while updating invoice table.
I found the solution for my problem.
Query should be
$query = "UPDATE `invoice` SET product_name = (select name from item where id = '{$_POST['productname'][$i]}'), quantity = '{$_POST['quantity'][$i]}', price = '{$_POST['price'][$i]}', discount = '{$_POST['discount'][$i]}', amount = '{$_POST['amount'][$i]}', dod = '{$dod}', added_by = '{$_SESSION['id']}' WHERE id = '{$_POST['pid'][$i]}' ";
mysqli_query($db, $query);

Display database values on option

I am trying to display the saved data in the database on select before a user can update other choice. I am not really sure how to code it. Can anyone come out with possible solution? Had tried many ways but unable to do so.
Update: I have found out the problem why the options does not show.
This is my code:
`
$consentId = $_GET['consent_id'];
$retrieveConsent = "SELECT * FROM consent, leavetype WHERE consent.type_of_leave = leavetype.type_of_leave";
$retrieveResult = mysqli_query($link, $retrieveConsent) or die("Retrieve Error" . mysqli_error($link));
$queryleavetype = "SELECT * FROM leavetype";
$queryleaveresult = mysqli_query($link, $queryleavetype) or die("Leave Retrieve Error " . mysqli_error($link));
$row = mysqli_fetch_array($retrieveResult);
mysqli_close($link);
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Edit Consent </title>
</head>
<body>
<div class="ui-content">
<h3><b>Edit Leave</b></h3>
<form action="doEditConsent.php" method="post" data-ajax="false">
<input type="hidden" name="cId" value="<?php echo $row['consent_id']; ?>"/>
<label for="dateFrom" ><b>Date From:</b></label>
<input type="date" id="dateFrom" name="newDateFrom" value="<?php echo $row['consent_date_from']; ?>" required>
<br>
<label for="dateTo" ><b>Date To:</b></label>
<input type="date" id="dateTo" name="newDateTo" value="<?php echo $row['consent_date_to']; ?>" required>
<br>
<label for="reason" ><b>Leave Type:</b></label>
<select name="leaveType" id="leaveType" data-mini="true">
<?php
while ($rowleave = mysqli_fetch_array($queryleaveresult)) {
?>
<option value="<?php echo $rowleave['type_of_leave']; ?>">
<?php echo $rowleave['leave_type']; ?>
</option>
<?php
};
?>
</select>
<br>
<button class="ui-btn ui-corner-all" type="submit" >Submit</button>
</form>
</div>
<?php
}
}
?>
</body>
</html>`
Try this, hopefully it will help you:
<select name="leaveType" id="leaveType" data-mini="true">
<option value=""></option>
<?php
$previous_selected_value = 'previous_selected_value';//get the previous value and assign it to this variable
while ($rowleave = mysqli_fetch_array($queryleaveresult)) {
$selected = ($rowleave['type_of_leave'] == $previous_selected_value) ? " selected='selected'" : "";
echo '<option value="'.$rowleave['type_of_leave'].'"'.$selected.'>'.$rowleave['leave_type'].'</option>';
}
?>
</select>

Categories