How to sum value from database and input value in textbox - php

here is my problem: I get the value of STOCK from the database and I input a value in textbox, the problem is that when I try to compute the system does not recognized or say undefined index: stock
here is the syntax from value to computation:
<td><input type = "text" name = "stock[]" size = "5" value = '<?php echo $row['stock']; ?>' disabled></td>
<td><input type = 'text' name = 'stockin[]' size = '5'></td>
<td><input type ="submit" name = "btn" value = "re-stock"></td>
here is the syntax for computation which I place after the tag
<?php
$capture_field_vals1="";
if(isset($_POST['btn']))
{
foreach($_POST['stockin'] as $key => $text_field){
$capture_field_vals1 .= $text_field;
}
echo $capture_field_vals1;
$num1 = $_POST['stock[]'];
$num2 = $_POST['$capture_field_vals1'];
$num3 = $num1 + $num2;
echo $num3;
}
?>

"[]" means array, at this point you might need to write more than one data to the database. Also in the PHP script, you could observe incoming post by var_dump($_POST);
<?php
if( isset($_POST["stock"]) ){
foreach ($_POST["stock"] as $key => $value) {
echo $value."<BR>";
}
}
?>
<form method="post" action="?">
<input type = "text" name = "stock[]" size = "5" value = '1'/>
<input type = "text" name = "stock[]" size = "5" value = '2'/>
<input type="submit">
</form>

Related

PHP Form array has empty values when inserting into MySQL table

I'm having an issue inserting php form array values into a MySQL table. Right now the form itself pulls worker information from another table to populate the fields and their values. Right now there are only three workers that would populate those fields, however as more workers get added, there could be as many as 40. When I add just the first worker from the form, all the information inserts normally. However, when I add more than one, the title and employeeId fields are blank and I can't figure out why. Any help would be greatly appreciated.
Here is the form:
<form method = 'POST' action = 'addworkers.php'>
<?php
$sql2 = "select * from workers where companyId = 1";
$result2 = mysqli_query($conn,$sql2);
$numRows = mysqli_num_rows($result2);
$check = 0;
while($row2 = $result2->fetch_assoc()) {
$employeeId = $row2["id"];
$name = $row2["name"];
echo '<input type="checkbox" name="employeeId[]" value="' . $employeeId . '">';
echo "$name\n";
echo '<input type = "hidden" value="' . $companyId . '" name = "companyId[]"/>';
echo '<input type = "hidden" value="' . $jobNumber . '" name = "jobNumber[]"/>';
echo 'Site Title : <input type = "text" name = "title[]"/><br/>';
}
?>
<input type="hidden" name="count" value="<?php echo "$numRows"; ?>"/>
<input type = 'submit' value = 'SEND'/>
</form>
Then the addworkers.php code
require_once("dbConfig.php");
session_start();
$timestamp = date("Y-m-d");
if (isset($_SESSION['loginname'])) {
$companyId = isset($_POST['companyId']) ? $_POST['companyId'] : "" ;
$jobNumber = isset($_POST['jobNumber']) ? $_POST['jobNumber'] : "" ;
$employeeId = isset($_POST['employeeId']) ? $_POST['employeeId'] : "" ;
$title = isset($_POST['title']) ? $_POST['title'] : "" ;
foreach($title as $key=>$value){
if (!empty($value)) {
$query = "insert into `Jobs` (id, companyId, jobId, employeeId, siteTitle, dateAdded) values (NULL,'$companyId[$key]', '$jobNumber[$key]','$employeeId[$key]','$value','$timestamp')";
$result = mysqli_query($conn,$query);
}
}
} else {
echo "Error";
}
I changed the echo "Error" line but the output was clear.
It must be a problem with how the array is counted but I'm not sure how to fix it. in the form, if I check the boxes next to each row, all the information is entered into the table properly. If I only check the second and/or third line, it doesn't include the Site Title and the employeeId is reversed.
Here is the output of the form:
<form method = 'POST' action = 'insertworkers.php'>
<input type="checkbox" name="employeeId[]" value="1">Mike
<input type = "hidden" value="1" name = "companyId"/>
<input type = "hidden" value="12345" name = "jobNumber"/>
Site Title : <input type = "text" name = "title[]"/>
<input type="checkbox" name="employeeId[]" value="2">Steve
<input type = "hidden" value="1" name = "companyId"/>
<input type = "hidden" value="12345" name = "jobNumber"/>
Site Title : <input type = "text" name = "title[]"/>
<input type="checkbox" name="employeeId[]" value="3">Roger
<input type = "hidden" value="1" name = "companyId"/>
<input type = "hidden" value="12345" name = "jobNumber"/>
Site Title : <input type = "text" name = "title[]"/>
<input type="hidden" name="count" value="3"/>
<input type = 'submit' value = 'SEND'/>
</form>
I also changed the foreach loop to a for loop since the array depth should be the same as all fields will be mandatory
require_once("dbConfig.php");
session_start();
$counter = "".$_POST["count"]."";
$timestamp = date("Y-m-d");
if ( isset( $_SESSION['loginname'] ) ) {
$companyId = isset($_POST['companyId']) ? $_POST['companyId'] : "" ;
$jobNumber = isset($_POST['jobNumber']) ? $_POST['jobNumber'] : "" ;
$employeeId = isset($_POST['employeeId']) ? $_POST['employeeId'] : "" ;
$title = isset($_POST['title']) ? $_POST['title'] : "" ;
for($i=0, $count = count($employeeId);$i<$count;$i++){
if (!empty($employeeId)) {
$query = "insert into `customerJobs` (id, companyId, jobId, employeeId, siteTitle, dateAdded) values (NULL,'$companyId', '$jobNumber','$employeeId[$i]','$title[$i]','$timestamp')";
$result = mysqli_query($conn,$query);
}
}
} else {
echo "Error";
}

How preserve my inputs values each time that I refresh my page?

I want to enter a name and a mark. As the mark entered is less or equal to 100, the names and marks entered is to be stored in an associative array when I click the submit button and it should request me to enter another name and marks. But if I enter a mark greater than 100 discarding the name entered, when I click the submit button, the php script should display me all the names and marks previously entered. Here what I have done but I am not getting the desired results. Please help. My code:
<?php
if(isset($_POST['lname']) && isset($_POST['marks'])){
$name = $_POST['lname'];
$marks = $_POST['marks'];
$lists = array($name => $marks);
foreach($lists as $name => $marks){
echo $name . '<br>';
echo $marks;
}
}
?>
<form action = "<?php echo $_SERVER['PHP_SELF'];?>" method = "POST">
Name:<br>
<input type = "text" name = "lname"><br><br>
Marks:<br>
<input type = "text" name = "marks"><br><br>
<input type = "submit" value = "Submit">
</form>
You can use session to achieve what you want, see this code:
<?php
session_start();
if(isset($_POST['lname']) && isset($_POST['marks'])){
if($_POST['marks'] > 100) {
$_SESSION['info'][] = array($_POST['lname'] => $_POST['marks']);
}
}
if(isset($_SESSION['info'])) {
for($i = 0; $i < count($_SESSION['info']); $i++) {
foreach($_SESSION['info'][$i] as $name => $marks){
echo '<p>' . $name . '<br>';
echo $marks . '</p>';
}
}
}
?>
<form action = "<?php echo $_SERVER['PHP_SELF'];?>" method = "POST">
Name:<br>
<input type = "text" name = "lname"><br><br>
Marks:<br>
<input type = "text" name = "marks"><br><br>
<input type = "submit" value = "Submit">
</form>
You should read some docs about session:
http://php.net/manual/en/intro.session.php
You are posting name and your server side is looking for lname

Undefined Offset when looking through an array to display values

Hey I am new to PHP and I am trying to take values from the user that were put into a form for a game. Every time the user enters text and clicks submit it should add it to the array. Every time it will show at the bottom of the page all the guesses currently in a ordered list until the user gets the right answer and wins.
<?php
$count =0;
$guesses = array();
if(isset($_POST['submit']))
{
$count = $_POST['count'];
for($r =0; $r < $count; $r++)
{
$guesses[$r] = $_POST['word'];
}
?>
<h3>Guess the word I'm thinking</h3>
<form action = "<?php echo $_SERVER['PHP_SELF'] ?>" method = "post">
<input type = "text" name = "word" value = "<?php echo $tell; ?>"/>
<input type = "hidden" name = "count" value = "<?php $count +=1;?>"/>
<input type = "submit" name ="submit" value = "Make a Guess"/>
</form>
<ol>
<?php
for($t=0; $t < $count; $t++)
{
?>
<li><?php echo $guesses[$t];?></li>
<?php
}
?>
</ol>
I keep getting a Undefined offset: 0. I did some reading and I know it has something to do with either me filling the array wrong or calling the index wrong. Hope you can help show me how to resolve this problem. Thank you.
The output would be similar to:
Your guesses:
1. blue
2. red
etc
Look if you don't want to use Session variable then you have to set the values enter by the user in the hidden input tag. Below is the code you might required to get your specific result:
<?php
$guesses="";
if(isset($_POST['submit']))
{
$guesses= $_POST['count']." ".$_POST['word'];
}
?>
<h3>Guess the word I'm thinking</h3>
<form action = "<?php echo $_SERVER['PHP_SELF'] ?>" method = "post">
<input type = "text" name = "word" value = "Word"/>
<input type = "hidden" name = "count" value = "<?php echo $guesses;?>"/>
<input type = "submit" name ="submit" value = "Make a Guess"/>
</form>
<ol>
<?php
$count = explode(" ", $guesses);
foreach($count as $val)
{
if($val!= ''){
?>
<li><?php echo $val;?></li>
<?php
}
}
?>
</ol>
EDITED:
Problem was that you foremost did not echo the $count in your form, you simply incremented it. So the post variable would be empty. Also, increment it after you add to the array instead of in the post.
<?php
if( !isset( $count ) ){
$count =0;
}
$guesses = array();
if(isset($_POST['submit'])) {
$guesses[$count] = $_POST['word'];
$count++;
}
?>
<h3>Guess the word I'm thinking</h3>
<form action = "<?php echo $_SERVER['PHP_SELF'] ?>" method = "post">
<input type = "text" name = "word" value = "<?php echo $tell; ?>"/>
<input type = "submit" name ="submit" value = "Make a Guess"/>
</form>
<ol>
<?php
for($t=0; $t < count( $guesses); $t++)
{
?>
<li><?php echo $guesses[$t];?></li>
<?php
}
?>
</ol>
Try this code:
<?php
$guesses = array();
if(isset($_POST['submit']))
{
if($_POST['guesses'] != '')
$guesses = explode('|', $_POST['guesses']);
if(trim($_POST['word']))
$guesses[] = trim($_POST['word']);
}
?>
<h3>Guess the word I'm thinking</h3>
<form action="<?php echo $_SERVER['PHP_SELF'] ?>" method="post">
<input type="text" name= "word" value="" />
<input type="hidden" name="guesses" value="<?php echo count($guesses)? implode('|',$guesses):''; ?>" />
<input type="submit" name="submit" value="Make a Guess" />
</form>
<ol>
<?php foreach($guesses as $guess) { ?>
<li><?php echo $guess;?></li>
<?php } ?>
</ol>

Form not outputting number [duplicate]

This question already has an answer here:
Output of numbers are incorrect sometimes.
(1 answer)
Closed 9 years ago.
Given an input of an expression consisting of a string of letters and operators (plus sign, minus sign, and letters. IE: ‘b-d+e-f’) and a file with a set of variable/value pairs separated by commas (i.e: a=1,b=7,c=3,d=14) write a program that would output the result of the inputted expression.
For example, if the expression input was ("a + b+c -d") and the file input was ( a=1,b=7,c=3,d=14) the output would be -3.
Thus far I have got this, it calculates the numbers but not sure how to calculate it by the letters abcd,
<html>
<head>
</head>
<body>
<form action = "" method = "GET">
Number 1: <input type = "text" name = "input[]" size=3>
<br/>
Number 2: <input type = "text" name = "input[]" size=3> <br>
Number 3: <input type = "text" name = "input[]" size=3> <br>
Number 4: <input type = "text" name = "input[]" size=3> <br>
<input type="hidden" name="calc" value ="yes">
<input type = "submit" name = "Calculate"/>
</form>
</body>
</html>
<?php
print_r($_GET);
$myInputs = $_GET['input'];
print_r($myInputs);
$myArray = array();
$myArray['a'] = 5;
$myArray['b'] = 10 ;
$myArray['c'] = 15 ;
$myArray['d'] = 20 ;
echo $myArray[$_GET['a']] + $myArray[$_GET['b']] ;
/*
if ($_GET['calc'] == "yes")
{
$a = $_GET['a'];
$b = $_GET['b'];
$c = $_GET['c'];
$d = $_GET['d'];
$total = $a+$b+$c+$d;
print "Total is: $total <p>";
}
*/
?>
<?php
$expression = '';
$input = array( 'a' => 5,
'b' => 10,
'c' => 15,
'd' => 20);
$total = 0;
$sum = '';
// Override default expression and input values
if(isset($_POST['Calculate']))
{
$input = $_POST['input']; //input being passed via POST method
$expression = $_POST['expression']; //expression being passed via POST method
}
// make sure the users expression is safe to use
if(preg_match('#^[a-z+-\s]+$#i', $expression))
{
$sum = $expression; //evaluates sum as expression
$input_letters = array(); //puts letters into a array
$input_operators = array(); //puts operators into a array
for ($i = 0; $i < strlen($expression) ; $i++) { //gets string length
if (($i % 2) == 0) {
$input_letters[] = $expression[$i]; //getting the character for the position i
} else {
$input_operators[] = $expression[$i];
}
}
//
for ($i = 0 ; $i < sizeof($input_letters); $i++) { //size of= numbers (4)
$value = $input[$input_letters[$i]]; //takes the value from the letters
if ($i == 0) {
$sum += $value; //adds the sum if = 0
} else {
if ($input_operators[$i-1] == '+') { //checks to see if the operator is +
$sum += $value;
} else if ($input_operators[$i-1] == '-') { //checks to see if the operator is -
$sum -= $value;
}
}
print_r($value);
}
} else {
echo "Error: expression not correct form"; //error message
}
?>
<form action="" method="post"> <!--Form begins-->
Number A: <input type="text" name="input[a]" value="<?php echo $input['a']; ?>" size=3> <br/>
Number B: <input type="text" name="input[b]" value="<?php echo $input['b']; ?>" size=3> <br>
Number C: <input type="text" name="input[c]" value="<?php echo $input['c']; ?>" size=3> <br>
Number D: <input type="text" name="input[d]" value="<?php echo $input['d']; ?>" size=3> <br>
<br>
Expression: <input type = "text" name = "expression" value="<?php echo $expression ?>"> =
<?php echo $sum; ?><br>
Sum: <?php echo $sum; ?><br>
<input type="submit" name="Calculate" />
</form>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script>
$( "form" ).submit(function( event ) {
var val_is_good=($('input[name="expression"]').val().length==4)?true:false;
if(!val_is_good){alert('Enter four letters or die!');}
});
</script>
Now I added a script to tell users if they enter more then 4 letters a alert message says please only enter four letters, would someone know why my script is outputing the alert message even when enter only four letters?
<html>
<head>
</head>
<body>
<form action = "" method = "GET">
Number 1: <input type = "text" name = "input[]" size=3>
<br/>
Number 2: <input type = "text" name = "input[]" size=3> <br>
Number 3: <input type = "text" name = "input[]" size=3> <br>
Number 4: <input type = "text" name = "input[]" size=3> <br>
<input type="hidden" name="calc" value ="yes">
<input type = "submit" name = "Calculate"/>
</form>
</body>
</html>
<?php
print_r($_GET);
$myInputs = $_GET['input'];
//you are assigning $_GET values to an array myInputs so no need here
print_r($myInputs);
echo $myInputs[0]+ $myInputs[1];
$myArray = array();
$myArray['a'] = 5;
$myArray['b'] = 10 ;
$myArray['c'] = 15 ;
$myArray['d'] = 20 ;
// In case of myarray it has keys a,b,c,d only... so need of using $_GET here also.
echo $myArray['a']+$myArray['b'];
// but if you want to it directly from$_GET values.
echo $_GET['input'][0]+ $_GET['input'][1];
?>
I found a solution at this site. Here is the code from that post:
<?php
$expression = '';
$input = array( 'a' => 5,
'b' => 10,
'c' => 15,
'd' => 20);
$total = 0;
$sum = '';
// Override default expression and input values
if(isset($_POST['Calculate']))
{
$input = $_POST['input'];
$expression = $_POST['expression'];
}
// make sure the users expression is safe to use
if(preg_match('#^[a-z+-\s]+$#i', $expression))
{
$sum = $expression;
$input_letters = array();
$input_operators = array();
for ($i = 0; $i < strlen($expression) ; $i++) {
if (($i % 2) == 0) {
$input_letters[] = $expression[$i];
} else {
$input_operators[] = $expression[$i];
}
}
//
for ($i = 0 ; $i < sizeof($input_letters); $i++) {
$value = $input[$input_letters[$i]];
if ($i == 0) {
$sum += $value;
} else {
if ($input_operators[$i-1] == '+') {
$sum += $value;
} else if ($input_operators[$i-1] == '-') {
$sum -= $value;
}
}
}
} else {
echo "Error: expression not correct form";
}
?>
<form action="" method="post">
Number A: <input type="text" name="input[a]" value="<?php echo $input['a']; ?>" size=3> <br/>
Number B: <input type="text" name="input[b]" value="<?php echo $input['b']; ?>" size=3> <br>
Number C: <input type="text" name="input[c]" value="<?php echo $input['c']; ?>" size=3> <br>
Number D: <input type="text" name="input[d]" value="<?php echo $input['d']; ?>" size=3> <br>
<br>
Expression: <input type = "text" name = "expression" value="<?php echo $expression ?>"> =
<?php echo $sum; ?><br>
Sum: <?php echo $sum; ?><br>
<input type="submit" name="Calculate" />
</form>

php Currentage not define in the scope

I am quite new to php. Can somebody please guide me what is wrong with the code.
<?php
if(!isset($_POST['submit']) || $_POST['submit']!="calculate")
{
$_POST['Contrib']="";
$_POST['Currentage']="";
$_POST['Retireage']="";
$Total =0;
$AnnGain =7;
}else{
$AnnGain = $_POST['AnnGain'];
$Years = $_POST['Retireage'] - $_POST['Currentage'];
$YearCount = 0;
$Total = $_POST['Contrib'];
while ($YearCount < $Years)
{
$Total = (round($Total) *(1.0 + $AnnGain/100) +
$_POST['Contrib']);
$YearCount = $YearCount+1;
}
}
?>
<b>A Retirement Saving calculator</b>
<form action="<?php echo $_SERVER['PHP_SELF'];?>" method="post">
<p> Your age now
<input type="text" size = "5" name = "Currentage"
value="<?php echo $_POST['Currentage'];?>">
<p> The age at which you want to retire
<Input type="text" SIZE="6" name="Retireage"
value="<?php echo $_POST['Retireage']; ?>">
<p> Annual Contribution
<input type="text" size = "15" name = "Contrib"
value="<?php echo $_POST['Contrib'];?>">
<p>Annual Return
<input type = "text" size = "5" NAME = "AnnGain"
value="<?php echo$AnnGain; ?>">
<BR><BR>
<p><b>Nest Egg </b>: <?php echo $Total; ?>
<p><Input type = "submit" Name = "submit" value = "calculate">
</form>
In your code i see:
input type="test"
It is wrong, it should be:
input type="text"
Input type should be text if you mean a textbox.
$_POST['Currentage']=="";
$_POST['Retireage']=="";
You're checking if $_POST['Currentage'] is equal to "" instead of setting it to "". What you want is $_POST['Currentage'] = "";. You have the same problem with $_POST['Retireage'].
outside of the fact that modifying $_POST variables is bad practice (just assign those values to a variable and use that in your code)
$_POST['Currentage']==""; should be $_POST['Currentage'] = '';
$_POST['Retireage']==""; should be $_POST['Retireage'] = '';
ALWAYS escape data using something like htmlentities() before you spit it out to the web browser to protect your page from injections. This is VERY important

Categories