Multi input values using foreach and calculating values - php

<input name="own_pools[]" type="text" value="'.$own_pools.'" id="own_pools" maxlength="5" size="5" >
when i print using: var_dump($_GET["own_pools"]); I get
array(4) {
[0]=> string(1) "5"
[1]=> string(3) "300"
[2]=> string(3) "280"
[3]=> string(2) "50"
}
the parameters in the link are showing correctly
index?own_pools[]=5&own_pools[]=300&own_pools[]=280&own_pools[]=50&visitor_expect=100000000&ticket_price=15&submit_calc=Calculate
but after that the values did not get the right data back in the form and shown like this:
How can I get it calculated and get the values correctly from the input and returned the entered values back to the input value.
I have searched and read but couldn't find the answer...
I have the following code
<?php
$ticket_price=0;
$visitor_expect=0;
$total_value=0;
$own_pools=0;
$pool_result=0;
if(isset($_GET['submit_calc']) && isset($_GET['own_pools'])) {
$ticket_price = $_GET['ticket_price'];
$visitor_expect =$_GET['visitor_expect'];
$own_pools=$_GET['own_pools'];
if(is_numeric($ticket_price) && is_numeric($visitor_expect)){
// pools calculations
$rev_visitors=((int)$_GET["visitor_expect"]* (int)$_GET["ticket_price"]);
$total_value=($rev_visitors*0.01)*30;
$pool_result = $total_value ;
}
}
?>
<form action="" method="get" >
<table>
<tr>
<?php
// Display headers in one row as colmun
$tds = '';
$sum_main_pools=0;
foreach( $calculations as $index =>$calculation ) {
?>
<th>
<?php echo $calculation['Calculation']['poolname']; ?>
</th>
<?php
// create TDs for the values
if ($calculation['Calculation']['poolname']<>"Regional Pool"){
$tds .= '<td>
<div class="input text" id="pool_calc">
' . $calculation['Calculation']['total_units'] . '
<input name="own_pools[]" type="text" value="'.$own_pools.'" id="own_pools" maxlength="5" size="5" >
</div>
</td>';
if(isset($_GET['own_pools'])){
$own_pools=(int)$_GET['own_pools'];
$global_calc=($own_pools * (int)$calculation['Calculation']['total_units']);
$sum_main_pools +=$global_calc;
}
} else {
$tds .= '<td>
' . $calculation['Calculation']['total_units'] . '
</td>';
}
}
var_dump($_GET["own_pools"]);
?>
</tr>
<tr>
<?php
// Printing the values
echo $tds;
?>
</tr>
</table>
<?php
$pool_result = $total_value + $sum_main_pools;
?>
<table>
<tr>
<td style="width: 30%">
<div class="input text" id="pool_calc">
Expected Visitors per day
<input name="visitor_expect" type="text" value="100000000" id="visitor_expect" maxlength="9" size="9" >
</div>
</td>
<td style="width: 30%">
<div class="input text" id="pool_calc">
Ticket Price
<input name="ticket_price" type="text" value="15" id="ticket_price" maxlength="2" size="3" >
</div>
</td>
</tr>
<tr >
<td style="width: 60%">
<div>
<label > <?php echo (isset($pool_result) ? $pool_result : "");?></label>
<input name="submit_calc" type="submit" value="Calculate" id="submit_calc">
</div>
</td>
</tr>
</table>
</form>

Solved it:
added in foreach a key in foreach
foreach( $calculations as $key =>$calculation ) {
and in input value added as array
<input name="own_pools[]" type="number" value="'.$own_pools.'" id="own_pools" maxlength="5" size="5" >
if(isset($_GET['own_pools'])){
$own_pools=(int)$_GET['own_pools'][$key];
$global_calc=($own_pools * (int)$calculation['Calculation']['total_units']);
$sum_main_pools +=$global_calc;
}

Related

How can I use 4 different input-values in php and save form?

I don't have much experience with php that's why I hope someone can help me to solve the problem.
I am trying to extend my database with new files. I need to be able to type in four different values in my form and save the form with the typed in values. If I only use the first input-tag #inschriftennummer1, it works. My saved form shows me what I've typed in. But I need three more inputs in order to tag the document with 4 values. If I use the code like that, no input value is shown when I save the form.
Maybe someone has a solution :)
<body>
<form name="Formular" method="post" action="">
<table style="width: 100%;">
<tr>
<td style="width: 0%;">
</td>
<td style="width: 85%;">
<?php
if (isset($_GET["change"]))
{
$xml = simplexml_load_file("Inschriften/".$_GET["change"].".xml");
echo '<input type="hidden" name="inschriftennummerAlt" value="'.$xml- >Inschriftennummer.'"/>';
echo '<input type="hidden" name="change"/>';
}
else
{
$xml = simplexml_load_file("Inschriften/Null.xml");
}
/*Gibt zu einem String die jeweilige Hexadezimalform zurück*/
function strToHex($string)
{
$hex='';
for ($i=0; $i < strlen($string); $i++)
{
$hex .= dechex(ord($string[$i]));
}
return str_replace("da", "", $hex);
}
/*Gibt zu einer Hexadezimalform den jeweiligen String zurück*/
function hexToStr($hex)
{
$string='';
for ($i=0; $i <strlen($hex)-1; $i+=2)
{
$string .= chr(hexdec($hex[$i].$hex[$i+1]));
}
return $string;
}
?>
<div class="main">
<div class="meta">
<table>
<tbody>
<tr>
<td colspan="2">
<?php
if (strlen($_GET["inschriftennummer"] == 0))
{
// echo "Bitte Inschriftennummer überprüfen.";
}
?>
</td>
</tr>
<tr>
<td class="I"><span class="label">Inschriftennummer</span>:</td>
<?php echo '<input type="hidden" name="inschriftvorher" value="'.$xml- >Inschriftennummer.'">'; ?>
<td class="II">
<input name="inschriftennummer1" type="text" size="7" value="<?php echo str_replace("_", " ", $xml->Inschriftennummer);?>"/>
<input name="inschriftennummer2" type="text" size="7" value="<?php echo str_replace("_", " ", $xml->Inschriftennummer);?>"/>
<input name="inschriftennummer3" type="text" size="7" value="<?php echo str_replace("_", " ", $xml->Inschriftennummer);?>"/>
<input name="inschriftennummer4" type="text" size="7" value="<?php echo str_replace("_", " ", $xml->Inschriftennummer);?>"/>
</td>

insert not functioning mysql php

i got one problem with this . everytime i go insert it the page just refresh and blank. i dont know where is the problem but i checked my sql the data i use is the same. so i dont know where the problem is.
<form enctype="multipart/form-data" method="POST"> <tr>
<td> Generic Name:<input type="text" class="form-control" name = "gname"></td>
</tr>
<tr>
<td> Brand Name:<input type="text" class="form-control" name = "bname"></td>
</tr>
<tr>
<td> Quantity:<input type="number" min="0" class="form-control" name = "mqty"></td>
</tr>
<tr>
<td> Description:<input type="text" class="form-control" name = "mdesc"></td>
</tr>
<br>
<tr>
<td> <input type="submit" class="btn btn-info" name="add" Value="Add"></td>
</tr>
</form>
<?php
include "../../functions/connect.php";
error_reporting(0);
date_default_timezone_set('Singapore');
$date = date('m/d/Y h:i:s a', time());
?>
<?php
include "../../functions/connect.php";
extract($_POST);
if(isset($add)){
$sql = "INSERT INTO `tbl_meds`(`date`,`generic`,`brand`,`description`,`medqty`) VALUES ('$date','$gname','$bname','$mdesc','$mqty')";
$result = mysql_query($sql) or die("Verification Error: " . mysql_error());
}
?>
EDIT: Result of var_dump($_POST) -
array(5) {
["gname"]=> string(11) "Paracetamol"
["bname"]=> string(8) "Biogesic"
["mqty"]=> string(3) "100"
["mdesc"]=> string(71) "The most prescribed Headache and Fever brand that's Effective and Safe."
["add"]=> string(4) "Save"
}
if(isset($_POST["add"])){
this will work for you
your form has POST method. So on PHP side you have to handle it with $_POST global variable.

Post form with multiple fields with same name attribute

I get a information from my DB and then I build a from based on the information. The idea is that I want to capture the score each players made in a game. This obviously mean that I would have an input field with the same name attribute of PID as well as for the score input field. My code looks like this:
<form name="enterscores" id="enterscores" method="post" action="parseFiles/parse_enterscores.php">
<b>Game number: </b> <input type="text" id="entergameID" name="entergameID" maxlength="10" size="10" placeholder="Game number" />
<hr />
<table width="50%">
<tr>
<td>
<b>First name</b>
</td>
<td>
<b>Last name</b>
</td>
<td>
<b>Score</b>
</td>
</tr>
<?php
foreach ($LoginIDs as $PID){
$Login_ID = $PID;
cleanNumber($Login_ID);
foreach (getPlayerDetails($Login_ID) as $playerdDetails) {
$Login_ID = (int)$playerdDetails->Login_ID;
$First_Name = $playerdDetails->First_Name;
$Last_Name = $playerdDetails->Last_Name;
?>
<tr>
<td>
<input type="hidden" name="PID" id="PID" value="<?php echo $Login_ID;?>" />
<?php echo $First_Name; ?>
</td>
<td>
<?php echo $Last_Name; ?>
</td>
<td>
<input type="hidden" id="number_of_players" name="number_of_players" value="<?php echo $number_of_players; ?>" />
<input type="text" id="playerscore" name="playerscore" placeholder="Score" maxlength="3" size="3" />
</td>
</tr>
<?php
}
}
?>
<tr>
<td>
<input type="submit" id="enterscoresbtn" name="enterscoresbtn" value="Submit scores" />
</td>
</tr>
</table>
</form>
<?php
}?>
On my parse page I have the following code:
<?php
if(!$_POST){
header('Location: ../');
exit;
}
if(isset($_POST['enterscoresbtn'])){
require_once (__DIR__ . '/../functions/functions.php');
echo '<pre>';
var_dump($_POST);
echo '</pre>';
$PIDs = $_POST['PID'];
print_r($PIDs);
$playerscores = $_POST['playerscore'];
$number_of_players = $_POST['number_of_players'];
cleanNumber($number_of_players);
// $player = array_combine($PIDs, $playerscores);
//print_r($player);
}?>
The output I get looks like this:
array(5) {
["entergameID"]=>
string(2) "15"
["PID"]=>
string(1) "9"
["number_of_players"]=>
string(1) "4"
["playerscore"]=>
string(3) "104"
["enterscoresbtn"]=>
string(13) "Submit scores"
}
How do I get to post these values and how would I be able to get each login id tie to the correct score on the parse page please?
create your inputs like <input name="playerscore[<?php echo $Login_ID ?>]" /> or something like that. this will give you post data like
$_POST['playerscore'] = array( 23=> 123, 42 => '<somePlayerScore>' /* and so on ... */ )
i would have written this as a comment, but this would not allow formatting the post propperly

arrange checkbox values in two columns

I have a form with check box values i want to arrange the checkbox in two columns instead of
one single long column.
How can i split it to two columns ?
Here is the code :
<form id="form" name="form" method="post" action="">
<table width="502" border="0">
<tr>
<td>
Name :
<input type="textbox" name="rcv_group_name" value="">
<input type="hidden" name="add" value="add" />
</td>
</tr>
<tr>
<td align="left">
<strong>HEADING</strong>
<?php
$q = "select * from Config_RCV";
$r = mysqli_query ($dbc, $q);
if (mysqli_num_rows($r) > 0)
{
$k=0;
while ($row = mysqli_fetch_array($r,MYSQLI_NUM))
{
?>
<br> <input type="checkbox" name ="rcv_val[]" value ="<? echo $row[0];?>" /> <? echo $row[1];?>
<?
$k++;
}
}
?>
</td>
</tr>
<tr>
<td align="right"><input type="submit" name="Submit" id="Submit" value="Submit" style="background-color:#999" />
< /td>
<td height="26" align="left"> </td>
<td> </td>
</tr>
</table>
<form>
add another table and make 2 columns by splitting 2'nd result:
if (mysqli_num_rows($r) > 0) {
$k=0;
echo '<table><tr>';
while ($row = mysqli_fetch_array($r,MYSQLI_NUM)) {
?>
<td><input type="checkbox" name ="rcv_val[]" value ="<?php echo $row[0];?>" /> <?php echo $row[1];?> </td>
<?php
$k++;
if($k%2 == 0){
echo '</tr><tr>';
}
}
echo '</table>';
}
use your $k
if ($k%2==0){
echo "<br />";
}
instead of the lone now
Using tables like above will probably be better for looks
You could just add a second column to your table:
echo "<tr>";
$i = 0;
while ($row = mysqli_fetch_array($r,MYSQLI_NUM)) {
if ($i++%2==0) {
echo "</tr><tr>";
}
echo "<td>".$CELL_CONTENT_HERE."</td>";
}
echo "</tr>";

Pass back values to form to populate it? (lots of values)

I need to pass back a large string of results to a form, so that the form can read those results from the URL and then populate the form with them. Problem is, the link ends up being:
&key=value&key=value ... until it can't process anymore (I assume a URL has a length limit?) resulting in my form not being able to fully populate. I need another way to pass values back to my form file.
VIEW.php file (basically just a table of values right as they are from the database, with the first column "id" being a link. When I click on "id", it goes back to my add.php(form page) and populates the form with the data matching that id)
<table border="0" cellpadding="0" cellspacing="0" id="table">
<thead>
<tr>
<th>ID</th>
<th>NAME</th>
<th>MANUFACTURER</th>
<th>MODEL</th>
<th>DESCRIPTION</th>
<th>ON HAND</th>
<th>REORDER</th>
<th>COST</th>
<th>PRICE</th>
<th>SALE</th>
<th>DISCOUNT</th>
<th>DELETED</th>
<th></th>
</tr>
</thead>
<tbody>
<?php } ?>
<?php
// loop to fetch data
while($row = mysql_fetch_array($result)) {
echo "<tr>";
echo "<td>
<a href='molszewski1_a2_add.php'>$row[id]</a></td>";
echo "<td>$row[name]</td>";
echo "<td>$row[manufac]</td>";
echo "<td>$row[model]</td>";
echo "<td>$row[descrip]</td>";
echo "<td>$row[onhand]</td>";
echo "<td>$row[reorder]</td>";
echo "<td>$row[cost]</td>";
echo "<td>$row[price]</td>";
echo "<td>$row[sale]</td>";
echo "<td>$row[discont]</td>";
echo "<td>$row[deleted]</td>";
$status = "$row[deleted]";
echo "<td><a href='molszewski1_a2_delete.php?id=$row[id]&flag=$status&sort=$sort'>";
$status = "$row[deleted]";
if ($status == 'n') {
$flag = "restore";
echo "delete";
} else if ( $status == 'y') {
$flag = "delete";
echo "restore";
}
echo "</a></td>";
echo "</tr>";
} ?>
<?php { ?>
</tbody>
</table>
ADD.php (form page where the form is supposed to fetch the data and populate it)
<?php
// If no form has been submitted, present form
if (empty($_GET))
{
add_form();
}
// if a form has been submitted
else
{
// if form_validity() == 1, proceed to connect
if (form_validity() == 1)
{
// connect to mysql + database
connect();
$saleItem = "n";
$discountItem = "n";
if( array_key_exists( 'saleItem', $_GET ) && $_GET['saleItem'] == 'y' )
{ $saleItem = "y"; }
if( array_key_exists( 'discountItem', $_GET ) && $_GET['discountItem'] == 'y' )
{ $discountItem = "y"; }
// get values from form, insert into database
$sql=("INSERT INTO inventory (name,
manufac,
model,
descrip,
onhand,
reorder,
cost,
price,
sale,
discont,
deleted)
VALUES ('$_GET[itemName]',
'$_GET[manufacturer]',
'$_GET[model]',
'$_GET[description]',
'$_GET[numberOnHand]',
'$_GET[reorderLevel]',
'$_GET[cost]',
'$_GET[sellingPrice]',
'$saleItem',
'$discountItem', 'n')");
// if the query doesn't work, display error message
if (!(mysql_query($sql))) { die ("could not query: " . mysql_error()); }
add_form();
// redirect to view.php after form submission
// use php instead
echo "<meta http-equiv='REFRESH' content='0;url=molszewski1_a2_view.php'>";
}
else
{
// if form is not valid (form_validity returns 0), display error messages
add_form();
}
}
?>
FUNCTIONS.php (all my functions for stuff like the form)
<?php function page_navigation(){ ?>
<div class="center">
<input type="button" value="ADD" />
<input type="button" value="VIEW" />
<input type="button" value="VIEW DELETED" />
<input type="button" value="VIEW ACTIVE" />
<br />
<br />
</div>
<?php } ?>
<?php function add_form() { ?>
<form action="molszewski1_a2_add.php" method="get" id="form">
<table width="529px">
<tr>
<td>ITEM NAME</td>
<td><input name="itemName" size="30" type="text" value="<?php echo $_GET["itemName"] ?>"/></td>
</tr>
<tr>
<td>MANUFACTURER</td>
<td><input name="manufacturer" size="30" type="text" value="<?php echo $_GET["manufacturer"] ?>"/></td>
</tr>
<tr>
<td>MODEL</td>
<td><input name="model" size="30" type="text" value="<?php echo $_GET["model"] ?>"/></td>
</tr>
<tr>
<td>DESCRIPTION</td>
<td><textarea name="description" rows="3" cols="20"><?php echo $_GET["description"] ?></textarea></td>
</tr>
<tr>
<td>ON HAND</td>
<td><input name="numberOnHand" size="30" type="text" value="<?php echo $_GET["numberOnHand"] ?>"/></td>
</tr>
<tr>
<td>REORDER LEVEL</td>
<td><input name="reorderLevel" size="30" type="text" value="<?php echo $_GET["reorderLevel"] ?>"/></td>
</tr>
<tr>
<td>COST</td>
<td><input name="cost" size="30" type="text" value="<?php echo $_GET["cost"] ?>"/></td>
</tr>
<tr>
<td>SELLING PRICE</td>
<td><input name="sellingPrice" size="30" type="text" value="<?php echo $_GET["sellingPrice"] ?>"/></td>
</tr>
<tr>
<td>SALE ITEM</td>
<td>
<input type="checkbox" name="saleItem" value="y" <?php if( isset( $_GET['saleItem'] ) ){ ?> checked="checked" <?php } ?> />
</td>
</tr>
<tr>
<td>DISCOUNTED ITEM</td>
<td>
<input type="checkbox" name="discountItem" value="y" <?php if( isset( $_GET['discountItem'] ) ){ ?> checked="checked" <?php } ?> />
</td>
</tr>
<tr>
<td colspan="2"><input type="submit" value="save" name="submit" id="submit" /></td>
</tr>
</table>
</form>
<?php } ?>
Use method="post" and $_POST (instead of $_GET).
POST requests can be much larger than GET requests as GET requests are limited by the maximum length of a URL. POST requests are limited by the size of the max_post_size ini-value which is usually a few megabytes.

Categories