Hidden Default Form Values - php

I've got a simple form that I would like to be able to add a hidden value that is only used in the event the user doesn't enter a value. The values are for simple text input fields and can use HTML, PHP, JavaScript, JQuery, or any combination thereof. Let me explain further that the value attributes are already set to contain the values in the DB for that form currently. However, in the event there is no current value in the DB for that specific field and the user does not enter a value themselves, I would like a default value to be passed in the POST.
I've done some research and found examples of custom attributes, etc... but these will not work for me. As I'm using an array builder that passes all of the fields in the form as a single array to a new function. Any help would be greatly appreciated!
The code shown below is the creation of the form... As you can see two separate fields are created redundantly for however many rounds exist within the tournament. I've also provided output HTML code of a two round form. In the event the DB has NULL values for the field in question, and if the user doesn't enter a value of his/her own, I would like to pass the value of "false".
$rchkpos = array();
$rchkscore = array();
for ($i=0; $i<=$tournament['numRounds']; $i++)
{
$rchkthis = array("$i" => "round".$i."pos");
$rchkthis2 = array("$i" => "round".$i."score");
$rchkpos = array_merge($rchkpos, $rchkthis);
$rchkscore = array_merge($rchkscore, $rchkthis2);
if ($i > 0)
{
$roundpos = $rchkpos[$i];
$roundscore = $rchkscore[$i];
if (!is_null($stats2[$roundpos])){
$roundposvar = "$stats2[$roundpos]";
}else{
$roundposvar = false;
}
if (!is_null($stats2[$roundscore])){
$roundscorevar = "$stats2[$roundscore]";
}else{
$roundscorevar = false;
}
$team_stats.="
<tr valign='top'>
<td align='center'>" . LANG_MAN_ROUND . " $i " . LANG_MAN_POSITION . "</td>
<td class='alt1' align='center'>
<input type='text' name='round[".$rchkpos[$i]."]' value='$stats2[$roundpos]' size='40' maxlength='5' />
</td>
</tr>
<tr valign='top'>
<td align='center'>" . LANG_MAN_ROUND . " $i " . LANG_MAN_SCORE . "</td>
<td class='alt1' align='center'>
<input type='text' name='round[".$rchkscore[$i]."]' value='$stats2[$roundscore]' size='40' maxlength='5' />
</td>
</tr>";
}
}
Output HTML Example:
<tbody><tr valign="top">
<td align="center">Round 1 Position</td>
<td align="center" class="alt1">
<input type="text" maxlength="5" size="40" value="2" name="round[round1pos]">
</td>
</tr>
<tr valign="top">
<td align="center">Round 1 Score</td>
<td align="center" class="alt1">
<input type="text" maxlength="5" size="40" value="false" name="round[round1score]">
</td>
</tr>
<tr valign="top">
<td align="center">Round 2 Position</td>
<td align="center" class="alt1">
<input type="text" maxlength="5" size="40" value="false" name="round[round2pos]">
</td>
</tr>
<tr valign="top">
<td align="center">Round 2 Score</td>
<td align="center" class="alt1">
<input type="text" maxlength="5" size="40" value="false" name="round[round2score]">
</td>
</tr>
</tbody>

You can possibly do it like this:
HTML
<input type="text" name="name" />
<input type="hidden" name="name_default" value="name_default" />
PHP (after form submit)
if(!isset($_POST['name'])) {
$_POST['name'] = $_POST['name_default'];
}
Or make an aray like this:
$array_check = array('name', 'telephone', 'gender');
foreach($array_check AS $key => $value) {
if(!isset($_POST[$value])) {
$_POST[$value] = $_POST[$value."_default"];
}
}
Keep in mind that users can edit the values of the hidden inputs (with developer tools like Firebug), always check the input!

Other possible approach is to set the default values in a dedicated property in each html input and then replace the value of the field before the post using jQuery:
// before post
$('input').each(function () {
if ($(this).val() == '')
$(this).val($(this).attr('defaultvalue'));
});

Related

PHP input field instant update after typing in values

just trying to make a little calculator for myself in php and i wonder if its possible to make the answer instant update after i type in the values?
Thank you.
<?php
if (isset($_POST['valuea'])) $valuea = $_POST['valuea'];
if (isset($_POST['valueb'])) $valueb = $_POST['valueb'];
if (isset($_POST['check1'])) {
$answer = (($valuea * $valueb) * 10)*2;
} else {
$answer = ($valuea * $valueb) * 10;
}
echo <<<_END
<form method='post' action=''>
<table border='0' width='500px' cellpadding='3' cellspacing='1' class="table">
<tr class="calcrow">
<td>Lenght:</td>
<td align="center"><input type='text' name='valuea' value="$valuea"/></td>
</tr>
<tr class="calcrow2">
<td>Width:</td>
<td align="center"><input type='text' name='valueb' value="$valueb"/></td>
</tr>
<tr class="calcrow2">
<td>2x test</td>
<td align="center"><input type="checkbox" name="check1"></td>
</tr>
<tr class="submit"><td colspan="2"><input type='submit' value='Calculate'/></td></tr>
_END;
?>
<tr class="calcrow">
<td><i>Answer</td>
<td align="center"><input type="text" value="<?php echo round($answer)?>"></td></i>
</tr>
</table>
</form>
You are looking for a thing called Jquery.
Which can fetch current Values of your form inputs or any other elements from your webpage. Then you can then send that data to your php file where you can perform the calculation and return the result which can again be displayed wherever you want .
All of this happens in real time.
This is the way you could do it if you wanted to do it in php
Else you could always go for plain JavaScript or a mixture of jquery + javascript, to avoid using php and ajax.

increment variable on submit to update mysql query

I am new to PHP(loving it already)
I have a form that looks up a table that sends 'golf hole' info back and allows a golfer to input their score of the hole. Problem I have is that I can present the first hole by looking up the hole_detail table but then cant figure out how loop through the table for hole 2, 3.....18 when the form is submitted. I have searched stackoverflow but cant find anything that specific about it. I have tried an if statement, if (isset($_POST['Submit'])) to try increment the $hole_id. Am I completely going about it the wrong way? Thanks in advance.
<?php
include ('../scripts/dbconfig.php');
# get the most recent course name:
$get_course_name = mysql_query("SELECT course_name FROM comp ORDER BY PID DESC LIMIT 1");
$show_course_name = mysql_fetch_array($get_course_name);
if (isset($_POST['Submit'])) {
$hole_id =1;
else {
$hole_id = $hole_id + 1;
}
}
# get the hole yardage and SI from most recent selected golf course:
$get_course_detail = mysql_query("SELECT * FROM `course_detail` WHERE course_name = '". $show_course_name['course_name'] . "'");
$show_course_detail = mysql_fetch_array($get_course_detail);
$get_hole_detail = mysql_query("SELECT * FROM `course_detail`,`phoenix_hole` WHERE Course_ID = 6 AND hole_id = $hole_id");
$show_hole_detail = mysql_fetch_array($get_hole_detail);
?>
</head>
<body>
<table width="300" cellspacing="0" cellpadding="0">
<tr>
<td width="40"><?php echo $show_course_name['course_name'];?></td>
</tr>
<tr>
<td width="20">HOLE <?php echo $show_hole_detail['hole_id']?></td>
<td width="5"> PAR <?php echo $show_hole_detail['hole_par'];?></td>
</tr>
<tr>
<td width="20">Yards</td>
<td width="20">S.I</td>
</tr>
<tr>
<td bgcolor="yellow"><?php echo $show_hole_detail['yellow_yards'];?></td>
<td><?php echo $show_hole_detail['hole_si'];?></td>
</tr>
<tr>
<td border="1px" bgcolor="white"><?php echo $show_hole_detail['white_yards'];?></td>
<td><?php echo $show_hole_detail['hole_si'];?></td>
</tr>
<tr>
<td bgcolor="red"><?php echo $show_hole_detail['red_yards'];?></td>
<td><?php echo $show_hole_detail['hole_si'];?></td>
</tr>
</table>
</p>
<form id="game_form" name="game_form" method="post" action="game_form.php">
<table width="300" border="0" align="left" cellpadding="2" cellspacing="0">
<tr>
<td><b>Hole Shots</b></td>
<td><input name="hole_shots" type="text" class="textfield" id="hole_shots" maxlength="2" size="3" ></td>
<td><b>Putts</b></td>
<td><input name="putts" type="text" class="textfield" id="putts" maxlength="2" size="3"></td>
</tr>
<tr>
<td> </td>
<td><input type="submit" name="Submit" value="Next Hole" align="center" /></td>
</tr>
</table>
</form>
</body>
</html>
Or you can use a hidden field that keeps the hole number and you can increment it from php.
$hole_id, in this scenario, will always be 1, because when a user clicks the Submit button, $_POST['Submit'] will always have a value. What you should do instead is have $_POST['Submit'] contain the value of $hole + 1. PHP is not going to "remember" what $hole_id was last time around; it's up to you to remind it. As soon as a request is sent to the browser--unless you're using sessions--PHP forgets everything about that request (HTTP is "stateless").
<?php
if (isset($_POST['Submit'])) {
$hole_id = (int)$_POST['Submit'];
} else {
$hole_id = 1;
}
# other code here
?>
You are on hole #<?php echo $hole_id; ?>.
<form>
<!-- form stuff here -->
<button type="submit" name="Submit" value="<?php echo $hole_id + 1; ?>">Next hole</button>
</form>

Inserting Dynamic amount of rows from Form into Table

Form:
<table width="100%" cellpadding="4" cellspacing="0" id="px">
<thead>
<tr class="tab_head">
<td width="25px" style="text-align:center; color:#FFFFFF; font-size:11px;">#</td>
<td class="form_label" style="color:#FFFFFF; font-size:11px;">First Name</td>
<td class="form_label" style="color:#FFFFFF; font-size:11px;">Last Name</td>
<td class="form_label" style="color:#FFFFFF; font-size:11px;">Wgt</td>
<td class="form_label" style="color:#FFFFFF; font-size:11px;">Address</td>
<td class="form_label" style="color:#FFFFFF; font-size:11px;">Phone</td>
<td class="form_label" style="color:#FFFFFF; font-size:11px;">Email</td>
<td></td>
</tr>
</thead>
<tbody id="tbl1">
<tr id="pass">
<td style="vertical-align:middle; text-align:center"><input type="text" name="pass_num[]" readonly="readonly" value="1" class="pass" style="font:Verdana; font-size:11px; border:none; background-color:transparent; width:25px; text-align:center; vertical-align:middle;" tabindex="-1"></td>
<td><input type="text" id="cfn1" name="cust_fname[]" class="form_g" /></td>
<td><input type="text" id="cln1" name="cust_lname[]" class="form_g" /></td>
<td><input type="text" name="cust_kg[]" class="form_a" /></td>
<td><input type="text" name="cust_addr[]" class="form_c" /></td>
<td><input type="text" name="cust_phone[]" class="form_g" /></td>
<td><input type="text" name="cust_email[]" class="form_b" /></td>
<td style="vertical-align:middle"><a class="removePax"><img src="images/remove_pax.png" /></a></td></tr>
</tbody>
</table>
Table Columns:
cust_id
cust_fname
cust_lname
cust_kg
cust_addr
cust_phone
cust_email
There is a snippet of JQuery that essentially clones the above table as required to allow the user to add another passenger etc. On submittinh, the data is posted to the next page fine, and I've tested numerous times that the data is coming through in Arrays (eg. $_POST[cust_fname] etc.).
The problem I'm having now is turning these into sets that I can insert into the table.
I tried a foreach loop and iterating but so far, I'm failing to come up with a solution. I have tried sorting the data into per passenger, but so far keeps clumping the data together.
JSFiddle
In your php code, you have to iterate with one for loop all the arrays in the same time and print them. Example :
cust_fname = $_POST["cust_fname"];
cust_lname = $_POST["cust_lname"];
for($i = 0; $i < count($cust_fname); $i++)
{
echo "Complete name : ".$cust_fname[$i]." ".$cust_lname[$i];
echo "<br/>";
}
I just put an example for two fields, you can do the rest :)
EDIT : I saw that you want to show them in a table, so you can change the code i gave you to :
cust_fname = $_POST["cust_fname"];
cust_lname = $_POST["cust_lname"];
echo "<table><tr><th>First name</th><th>Last Name</th></tr><tbody>";
for($i = 0; $i < count($cust_fname); $i++)
{
echo "<tr>";
echo "<td>".$cust_fname[$i]."</td><td> ".$cust_lname[$i]."</td>";
echo "</tr>";
}
echo "</tbody></table">;

Undefined index with $_POST function

So I Basically copied the following code, execpt renaming columns names.
The form is folowing:
<table align="left" width="30%" border="0" >
<form action="company_edit_php.php" method="post">
<tr><td align="center" bgcolor="#ECE6E6">Location: <td align="center"> <input type="text" value="<?php echo $row['Location']?>"/><br></td></tr>
<tr><td align="center" bgcolor="#ECE6E6">User: <td align="center"> <input type="text" value="<?php echo $row['User']?>"/><br></td></tr>
<tr><td align="center" bgcolor="#ECE6E6">Telephone: <td align="center"> <input type="text" value="<?php echo $row['Telephone']?>"/><br></td></tr>
<tr><td align="center" bgcolor="#ECE6E6">Email: <td align="center"> <input type="text" value="<?php echo $row['Email']?>"/><br></td></tr>
<td> <input type="submit" value="Change" /></td></tr>
And PHP code:
<?php
$con = mysql_connect("localhost","username","password");
$id = isset($_GET['id']) ? (int)$_GET['id']: 1;
mysql_select_db("Database", $con);
if (isset($_POST['Location'])) {
echo $_POST['Location'];
} else {
echo 'empty';
}
$Location = $_POST['Location'];
Result of this code is Undefined index: Location and from if statement i get "empty".
Why this same code work for another page? What should I do now?
Thank you for your efforts
To correct the index post, use this command at the beginning of the file and uses the variable $Location
$Location = (isset($_POST["Location"])?$_POST["Location"]:"");
You have to change your form because you miss name into your input and to retrieve the value with $_GET you have to use it like this:
<tr><td align="center" bgcolor="#ECE6E6">Location: <td align="center"> <input type="text" name="Location" value="<?php echo $row['Location']?>"/><br></td></tr>
To get the value of textboxes, you need to give them name
<table align="left" width="30%" border="0" >
<form action="company_edit_php.php" method="post">
<tr><td align="center" bgcolor="#ECE6E6">Location: <td align="center"> <input type="text" value="<?php echo $row['Location']?>" name='location'/><br></td></tr>
<tr><td align="center" bgcolor="#ECE6E6">User: <td align="center"> <input type="text" value="<?php echo $row['User']?>" name='user'/><br></td></tr>
<tr><td align="center" bgcolor="#ECE6E6">Telephone: <td align="center"> <input type="text" value="<?php echo $row['Telephone']?>" name='phone'/><br></td></tr>
<tr><td align="center" bgcolor="#ECE6E6">Email: <td align="center"> <input type="text" value="<?php echo $row['Email']?>" name='mail'/><br></td></tr>
<td> <input type="submit" value="Change" /></td></tr>
Location is not passed in the code that you show. for that reason $_POST['Location'] is undefined. put it inside your if statement to avoid the error.
like:
$Location = 'empty';
if (isset($_POST['Location'])) {
echo $_POST['Location'];
$Location = $_POST['Location'];
} else {
echo 'empty';
}
Complete form
<table align="left" width="30%" border="0" >
<form action="company_edit_php.php" method="post">
<tr><td align="center" bgcolor="#ECE6E6">Location: <td align="center"> <input type="text" value="<?php echo $row['Location']?>"/><br></td></tr>
<tr><td align="center" bgcolor="#ECE6E6">User: <td align="center"> <input type="text" value="<?php echo $row['User']?>"/><br></td></tr>
<tr><td align="center" bgcolor="#ECE6E6">Telephone: <td align="center"> <input type="text" value="<?php echo $row['Telephone']?>"/><br></td></tr>
<tr><td align="center" bgcolor="#ECE6E6">Email: <td align="center"> <input type="text" value="<?php echo $row['Email']?>"/><br></td></tr>
<td> <input type="submit" value="Change" /></td></tr>
Try this:
<?php
$con = mysql_connect("localhost","username","password");
$id = isset($_GET['id']) ? (int)$_GET['id']: 1;
mysql_select_db("Database", $con);
$location= "";
if (isset($_POST['Location'])) {
$location= $_POST['Location']; // <------------- put this here!
//echo $_POST['Location'];
} else {
echo 'empty';
}
echo $location; // <------------- added this
//$Location = $_POST['Location']; // it was erroring here as I am guessing that you were sometimes accessing the page without posting the location. If the variable does not exist, you cannot echo it.. thus the changes above
From what you are writing it is so that either there is no field named "Location" on the page you made, or it is outside of the form (thus not inside ....).
As it works on the site where the original sourcecode has been taken from there are only 2 options there.
The site in question HAS a field named location inside the appropriate form
The site in question suppresses the error message that would come.
In order for your code to work you would need to 1.) put the field "Location" inside the form if it is not already and 2.) You need to "secure" the getting of the variable so that an error is not shown even if Location is empty.
I'm giving different examples for both variants:
1.) Putting Location inside the form
<form action="company_edit.php" method="post">
......
<input type="text" name="Location" id="Location>
......
</form>
2.) Making sure that the error does not occur even if Location does notee xist,....
I would even advice doing the following step for every $_POST and $_GET variable you want
to use in your application as it reduces the chance of the error message that a specific
$_GET/$_POST is not set considerably (although for debugging and finding writing errors
it is good to have the error messages).
if (isset($_POST['Location'])
$Location = $_POST['Location'];
else
$Location='';
On another note as you are giving parameters via POST and you don't put the id into the URL the $_GET of id will always result in an empty id field (thus the "1" is always used as id). For it to work you would either need to use id as post and put an appropriate field into the form or you would have to eidt the "action" part of the form so that id is given as "?id=" parameter there

unable to get the value of the text field with the help of respective checkboxes. please help

I've a doubt. I've 3 textboxes and each is having checkboxes next to it. I want to display
the values of only those textboxes whose respective checkboxes are clicked. Following is the attached HTML and PHP codes:
<html>
<head>
</head>
<body>
<form name="f" method="post" action="4.php">
<table>
<tr>
<th> Facility </th>
</tr>
<tr>
<td><input type="text" name="a1" value="a"></td><td><input type="checkbox" id="facility[]" name="facility[]" value="Hostel"></td>
</tr>
<tr>
<td><input type="text" name="b1" value="b"></td><td><input type="checkbox" id="facility[]" name="facility[]" value="Transport"></td>
</tr>
<tr>
<td><input type="text" name="c1" value="c"></td><td><input type="checkbox" id="facility[]" name="facility[]" value="Food"></td>
</tr>
<tr>
<td colspan="3"><input type="submit" value="submit" /></td>
</tr>
</table>
</form>
</body>
</html>
and below is the PHP part.
<?php
$a=$_POST['a1'];
$b=$_POST['b1'];
$c=$_POST['c1'];
$facilityArray = $_POST['facility'];
$facility = "";
if(count($facilityArray) > 0)
{
foreach($facilityArray as $fac)
{
$facility .= " " . $fac;
}
}
echo $facility; echo "<br>";
echo $a; echo "<br>";
echo $b; echo "<br>";
echo $c;
?>
With the help of following codes I am able to display all the values of checked checkboxes. I am also able to display the values of all the textboxes. But I actually want to display the values of only those textboxes whose respective checkboxes are clicked. I know it may be a very basic question but please help me grow in PHP. Thanks in advance... :(
Your textboxes should also be in an array post to achieve this.
To achieve this change the input lines as:
<td><input type="text" name="textboxes[]" value="a"></td><td><input type="checkbox" id="facility[]" name="facility[]"></td>
From php you'll be getting the posted textboxes in an array as:
$textbox=$_POST['textboxes'];
You should then loop through the checkboxes array and if the corresponding checkbox is "on" (clicked), then display the textboxes value. To do this you would also need a counter to make sure you are on the same array index for both checkboxes and textboxes:
if(count($facilityArray) > 0)
{
$i = 0;
foreach($facilityArray as $fac)
{
if($fac == "on")
{
echo $textbox[$i] . "</br>";
}
$i ++;
}
}
I've also added a name to your submit button so you only check the form when it is submitted.
Your page should now look something like this:
<?php
if(isset($_POST['submit']))
{
$textbox=$_POST['textboxes'];
$facilityArray = $_POST['facility'];
if(count($facilityArray) > 0)
{
$i = 0;
foreach($facilityArray as $fac)
{
if($fac == "on")
{
echo $textbox[$i] . "</br>";
}
$i ++;
}
}
}
?>
<form name="f" method="post" action="4.php">
<table>
<tr>
<th> Facility </th>
</tr>
<tr>
<td><input type="text" name="textboxes[]" value="a"></td><td><input type="checkbox" id="facility[]" name="facility[]"></td>
</tr>
<tr>
<td><input type="text" name="textboxes[]" value="b"></td><td><input type="checkbox" id="facility[]" name="facility[]"></td>
</tr>
<tr>
<td><input type="text" name="textboxes[]" value="c"></td><td><input type="checkbox" id="facility[]" name="facility[]"></td>
</tr>
<tr>
<td colspan="3"><input name="submit" type="submit" value="submit" /></td>
</tr>
</table>
</form>
UPDATE:
To make sure that the $_POST variable exists before assigning it to a variable we use the isset(). In your case just update the php segment as:
<?php
if(isset($_POST['submit']))
{
if(isset($_POST['textboxes']))
{
$textbox=$_POST['textboxes'];
if(isset($_POST['facility']))
{
$facilityArray = $_POST['facility'];
if(count($facilityArray) > 0)
{
$i = 0;
foreach($facilityArray as $fac)
{
if($fac == "on")
{
echo $textbox[$i] . "</br>";
}
$i ++;
}
}
}
}
}
?>
Where the only changes are the addition of another two if statements that take a boolean flag from the isset() function according to whether the $_POST variable has been posted successfully
if(isset($_POST['textboxes']))
AND
if(isset($_POST['facility']))

Categories