how to fix this undefined variable - php

On a Previous page the user enters in a number in the textbox, when that form is submitted, the number is posted on this page as $_SESSION['sessionNum']. Now I want to store this number on the top as $sessionMinus showing the same number except difference is that everytime this form is submitted to it self, the number counts down by 1 everytime the form is submitted. Problem is that it is giving me an undefined variable $sessionMinus. How can this be fixed?
<?php
session_start();
//validate the post data if necessary
if (isset($_POST['sessionNum'])) {
$_SESSION['sessionNum'] = $_POST['sessionNum'];
}else{
$_SESSION['sessionNum']--;
}
$sessionMinus = $_SESSION['sessionNum'];
?>
<body>
<?php echo $sessionMinus; ?>
<form id="enter"
action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>"
method="post"
onsubmit="return validateForm(this);" >
<p>
<input id="submitBtn" name="submitDetails" type="submit" value="Submit Details" />
</p>
</form>
<?php
$outputDetails = "";
$outputDetails .= "
<table id='sessionDetails' border='1'>
<tr>
<th>Number of Sessions:</th>
<th>{$_SESSION['sessionNum']}</th>
</tr>";
$outputDetails .= "</table>";
echo $outputDetails;
?>
</body>

Your $sessionMinus is never initialized.
When you do isset($sessionMinus) you're checking if the variable has been declared, and since it hasn't, it will of course be undefined. If you want variables to be carried across each submit, you have to store it in a $_SESSION variable, not a local variable.
You can learn about variable scope here and about session variables here.
You're using $_POST
You're using $_POST but you're not sending a variable named sessionNum in your form.
Keep it clean
You should also try to keep your html as "clean" as possible, by separating PHP processing and PHP outputting.
This is how your setup should look like
<?php
session_start();
if(!isset($_SESSION['my_counter'])){
if(isset($_POST['my_count'])){
//Declare my counter for the first time
$_SESSION['initial_count'] = $_POST['my_count'];
$_SESSION['my_counter'] = $_POST['my_count'];
}
}else{
//Decrement my counter
$_SESSION['my_counter']--;
}
$actionurl = htmlentities($_SERVER['PHP_SELF']);
if($_SESSION['my_counter'] <= 0)
$number_of_sessions = "No sessions left!";
else
$number_of_sessions = $_SESSION['my_counter'];
$started_with_sessions = $_SESSION['initial_count'];
?>
<!DOCTYPE html>
<body>
<form id="enter" action="<?php echo $actionurl; ?>" method="post" onsubmit="return validateForm(this);" >
<input type='hidden' name='my_count' value='5' />
<input id="submitBtn" name="submitDetails" type="submit" value="Submit Details" />
</form>
<table id='sessionDetails' border='1'>
<tr>
<th>Number of sessions: </th>
<th><?php echo $number_of_sessions; ?></th>
</tr>
<tr>
<th>Started with: </th>
<th><?php echo $started_with_sessions; ?> sessions</th>
</tr>
</table>
</body>
</html>

if $sessionMinus is not set, you are never setting it. Perhaps you should be checking if it's not set before you set it?
if (!isset($sessionMinus)) {
$sessionMinus = "";
$sessionMinus .= $_POST['sessionNum']--;
}

Related

After button click I want to display the table and open new window

Only after first execution table is displayed and also outs_print.php file is displayed in new tab when again executed outward_print.php file is displayed in same tab.
I want table(outs_print.php file) to be displayed in new tab after button is clicked.
<!doctype html>
<body>
<form name="out_print" action="out_print.php" method="post">
<table class="table_1">
<tr><td><label>Date Range From</label></td>
<td><input type="date" name="from" /></td>
<td><label>To</label></td>
<td><input type="date" name="to"/></td></tr>
<tr><td><label>Name</label></td>
<td><input type="text" name="name" /></td></tr></table>
<input type="submit" name="submit" value="Search" onclick="myFunction();" class="button3"/>
<script>
function myFunction()
{
document.out_print.action = "outs_print.php";
document.out_print.submit();
}
</script>
</form>
</body>
</html>
outs_print.php
<?php
$connection = mysql_connect("localhost", "root", "");
$db = mysql_select_db("prs", $connection);
if(isset($_POST['submit'])){
$name = $_POST['name'];
$from = $_POST['from'];
$to = $_POST['to'];
if($name !=''||$from !=''||$to !='')
{
?>
<html>
<body>
<table border="1" bordercolor="#d6d6d6" class="tabl">
<thead bgcolor="#FAFAFA">
<tr>
<th>No</th>
<th>Date</th>
<th>Name</th>
<th>Price</th>
</tr>
</thead>
<tbody>
<?php
$sql = "SELECT * FROM out WHERE (date between '$from' and '$to') AND (name = '$name')";
$records=mysql_query($sql);
while($out=mysql_fetch_assoc($records))
{
echo "<tr>";
echo "<td>".$out['no']."</td>";
echo "<td>".$out['date']."</td>";
echo "<td>".$out['name']."</td>";
echo "<td>".$out['price']."</td>";
echo "</tr>";
}
?>
<script type="text/javascript">
alert("Okay");
var win = window.open("out_print.php", "out_print.php");
win.focus();
</script>
<?php
}
}
?>
</tbody>
</table>
</body>
</html>
The other answers here are on the right track, but target="_blank" will create a new tab/window with each form submission.
If you want a new tab/window to be launched on the first submission of the form, and any subsequent submissions of the form to return their result in the tab/window which was created on the first submission, giving the target a name will do that.
<form name="out_print" method="post" action="out_print.php" target="out_print_response">
....
http://www.w3schools.com/tags/att_form_target.asp
Just add target="_blank" to the form element :)
http://www.w3schools.com/tags/tag_form.asp
add target="_blank" like this:
<form name="out_print" action="out_print.php" method="post" target="_blank">
target attribute in form specifies where to display the response that is received after submitting the form. target="_blank" display the response in new tab.
Hope this helps.

While loop $_post from form

<?php
include("dbFunctions.php");
$query ="SELECT * FROM `physical_examination` WHERE `PE_Opt_ans`= 0";//select form options name
$result = mysqli_query($link,$query);
?>
<div id="tabs-3">
<table>
<form action="<?php echo $_SERVER['PHP_SELF']?>" method="post" name="tab0">
<?php while ($arrayResult = mysqli_fetch_array($result)){ ?>
<tr>
<td><label for="input"><b><?php echo $arrayResult['PE_Opt_name']?></label></td>
<?php if ($arrayResult['PE_Opt_type'] == "textarea") { ?>
<td><textarea rows="8" cols="45"name = "other1"></textarea></td>
<?php } else { ?>
<td><input type="<?php echo $arrayResult['PE_Opt_type']?>" name="input<?php echo $arrayResult['id']?> " ></td>
</tr>
<?php } ?>
<?php } ?>
<br> <input value="Submit" type="submit" name="submit1">
</form>
</table>
<?php
include "dbFunctions.php";
if(isset($_POST['submit1'])) {
$number = $_POST['other1'];
I am stuck here.
How do I $_POST the form based on the while loop after I click on submit button? Do I need another while loop again for the name value of input <?php echo $arrayResult['id']?>
I didn't quiet get what you want but i assume you want the contents of the textarea generated by the while loop.
Change in your loop the names from input to input[] and other1 to other1[]
If you var_dump($_POST) afterwards you should see that they are now an array which you can loop over with foreach
PS: You should NEVER EVER eat raw $_POST/$_GET inputs and PHP_SELF is another security breach. But that's just my two cents

Multiple row insert to table if check box is selected

I am trying to insert multiple rows to a database table if check box is selected. But in my code when I am trying to insert, new rows are inserting based on check box selection. But no data is passing. I need some advice on below code to modify:
<?php
$db=mysql_connect("localhost","root","");
mysql_select_db("kkk",$db);
$qry="select * from pi";
$result=mysql_query($qry);
?>
<form action="check.php" method="post">
<table>
<tr>
<th>A</th>
<th>B</th>
<th>C</th>
</tr>
<?php
while($row=mysql_fetch_array($result))
{
echo "<tr><td><input type=checkbox name=name[] value='".$row['id']."'>".$row['PI_NO']."</td><td>".$row['CUSTOMER_NAME']."</td><td>".$row['PI_ADDRESS']."</td></tr>";
}
?>
<input type="submit" value="save" id="submit">
<?php
$db=mysql_connect("localhost","root","");
mysql_select_db("kkk",$db);
$name=$_POST['name'];
foreach($_POST['name'] as $x)
{
$qry="INSERT INTO pi (PI_NO, CUSTOMER_NAME, PI_ADDRESS)VALUES ('$PI_NO','$CUSTOMER_NAME','$PI_ADDRESS')";
mysql_query($qry);
}
?>
Notes:
You forgot to bind the name of your checkbox using a single tick (')
You used variables in your query which you didn't defined and assigned value with yet
You only passed on the value of name, and did not include the Pi Address and Customer name. I'll be passing them by hidden input using <input type="hidden">.
I'll change the way you check your passed on form by looping them and check them using for() and if()
Use mysql_real_escape_string() before using them in your queries to prevent some of the SQL injections. But better if you consider using mysqli prepared statement rather than the deprecated mysql_*.
Is your post a single file? If it is, you must enclose your query using an isset() to prevent error upon loading the page.
You didn't close your <form>
Here's your corrected while loop:
<?php
while($row=mysql_fetch_array($result))
{
?>
<tr>
<td>
<input type="checkbox" name="name[]" value="<?php echo $row['id']; ?>">
<?php echo $row["PI_NO"]; ?>
<!-- HERE IS THE START OF YOUR TWO HIDDEN INPUT -->
<input type="hidden" name="piaddress[]" value="<?php echo $row["PI_ADDRESS"]; ?>">
<input type="hidden" name="customer[]" value="<?php echo $row["CUSTOMER_NAME"]; ?>">
</td>
<td><?php echo $row['CUSTOMER_NAME']; ?></td>
<td><?php echo $row['PI_ADDRESS']; ?></td>
</tr>
<?php
} /* END OF WHILE LOOP */
?>
<input type="submit" value="save" id="submit">
</form> <!-- YOU DID NOT CLOSE YOUR FORM IN YOUR POST -->
And your query:
<?php
$db=mysql_connect("localhost","root","");
mysql_select_db("kkk",$db);
$counter = count($_POST["name"]); /* COUNT THE PASSED ON NAME */
for($x=0; $x<=$counter; $x++){
if(!empty($_POST["name"][$x])){
$PI_NO = mysql_real_escape_string($_POST["name"][$x]);
$CUSTOMER_NAME = mysql_real_escape_string($_POST["customer"][$x]);
$PI_ADDRESS = mysql_real_escape_string($_POST["piaddress"][$x]);
$qry="INSERT INTO pi (PI_NO, CUSTOMER_NAME, PI_ADDRESS) VALUES ('$PI_NO','$CUSTOMER_NAME','$PI_ADDRESS')";
mysql_query($qry);
} /* END OF CHECKING THE CHECKBOX IF SELECTED */
} /* END OF FOR LOOP */
?>
Lots of little problems. And some big ones.
as $x){ .. $x is not being used so I assume you just loop for the number of checked boxes.
These have no values: '$PI_NO','$CUSTOMER_NAME','$PI_ADDRESS'
Missing </form>
Not being used: $name=$_POST['name'];
<?php
echo '<form action="check.php" method="post"><table><tr><th>A</th><th>B</th><th>C</th></tr>';
$db=mysql_connect("localhost","root","");
mysql_select_db("kkk",$db);
$sql = "select `id`,`PI_NO`, `CUSTOMER_NAME` ,`PI_ADDRESS` from `pi`";
$result=mysql_query($sql);
while($row=mysql_fetch_array($result)){
echo "<tr><td><input type=\"checkbox\" name=\"name[]\" value=/"$row[0]/"'>$row[1]</td><td>$row[2]</td><td>$row[3]</td></tr>";
}
echo '<input type="submit" value="save" id="submit"></form>';
foreach($_POST['name'] as $x){
$sql="INSERT INTO pi (`PI_NO`, `CUSTOMER_NAME`, `PI_ADDRESS`)VALUES ('$PI_NO','$CUSTOMER_NAME','$PI_ADDRESS')";
mysql_query($sql);
}
?>

How to call php function from html form action?

I want to call php function in form action and i want to pass id as a argument. What I am doing is, in html form database column values will be displayed in text boxes, If I edit those values and click 'update' button values in database should be updated and 'Record updated successfully'message should be displayed in same page. I tried below code but not working. Let me know the solution. Thanks in advance.
<html>
<head>
<link rel="stylesheet" type="text/css" href="cms_style.css">
</head>
<?php
$ResumeID = $_GET['id'];
$con = mysql_connect("localhost", "root", "");
mysql_select_db("engg",$con);
$sql="SELECT * from data WHERE ResumeID=$ResumeID";
$result = mysql_query($sql);
$Row=mysql_fetch_row($result);
function updateRecord()
{
//If(!isset($_GET['id']))
//{
$NameoftheCandidate=$_POST[NameoftheCandidate];
$TelephoneNo=$_POST[TelephoneNo];
$Email=$_POST[Email];
$sql="UPDATE data SET NameoftheCandidate='$_POST[NameoftheCandidate]', TelephoneNo='$_POST[TelephoneNo]', Email='$_POST[Email]' WHERE ResumeID=$ResumeID ";
if(mysql_query($sql))
echo "<p>Record updated Successfully</p>";
else
echo "<p>Record update failed</p>";
while ($Row=mysql_fetch_array($result)) {
echo ("<td>$Row[ResumeID]</td>");
echo ("<td>$Row[NameoftheCandidate]</td>");
echo ("<td>$Row[TelephoneNo]</td>");
echo ("<td>$Row[Email]</td>");
} // end of while
} // end of update function
?>
<body>
<h2 align="center">Update the Record</h2>
<form align="center" action="updateRecord()" method="post">
<table align="center">
<input type="hidden" name="resumeid" value="<? echo "$Row[1]"?>">
<? echo "<tr> <td> Resume ID </td> <td>$Row[1]</td> </tr>" ?>
<div align="center">
<tr>
<td> Name of the Candidate</td>
<td><input type="text" name="NameoftheCandidate"
size="25" value="<? echo "$Row[0]"? >"></td>
</tr>
<tr>
<td>TelephoneNo</td>
<td><input type="text" name="TelephoneNo" size="25" value="<? echo "$Row[1]"?>"></td>
</tr>
<tr>
<td>Email</td>
<td><input type="text" name="Email" size="25" value="<? echo "$Row[3]"?>">
</td>
</tr>
<tr>
<td></td>
<td align="center"><input type="submit" name="submitvalue" value="UPDATE" ></td>
</tr>
</div>
</table>
</form>
</body>
</html>
try this way
HTML
<form align="center" action="yourpage.php?func_name=updateRecord" method="post">
PHP
$form_action_func = $_POST['func_name'];
if (function_exists($form_action_func)) {
updateRecord();
}
write form action="" and then write your php code as below
note : use form method as get
<?php
if(isset($_GET['id']))
{
call your function here
}
?>
in function access all values using $_GET['fieldname']
simple way make your "Submit " and "Update" action performed on same page then
if(isset($_POST['update']))
{
//perform update task
update($var1,var2,$etc); // pass variables to function
header('Location: http://www.example.com/');// link to your form
}
else if(isset($_POST['submit']))
{
//perform update task
submit($var1,$var2,$etc);// pass variables to function
header('Location: http://www.example.com/'); // link to next page after submit successfully
}
else
{
// display form
}

Simple POST random number issue in PHP

Ok I am trying to make something to ask you random multiplication questions. Now it asks the questions fine. Generates the random questions fine. But when it reloads the page the random numbers are different...
how can I fix this?
<?php
$rndnum1 = rand(1, 12);
$rndnum2 = rand(1, 12);
echo "<h3>". $rndnum1 . " x ";
echo $rndnum2 . "</h3>";
if($_SERVER["REQUEST_METHOD"] == "GET") {
$answer=0;
}
else if($_SERVER["REQUEST_METHOD"] == "POST") {
$answer=trim($_POST["answerInput"]);
$check=$rndnum1*$rndnum2;
if($answer==$check) {
echo "Correct!";
}
else {
echo "Wrong!";
}
}
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" >
<table>
<tr>
<td>
First Name:
</td>
<td>
<input type="text" name="answerInput" value="<?php echo $answer; ?>" size="20"/>
</td>
<td>
<?php echo $answerError; ?>
</td>
</tr>
<tr>
<td class="signupTd" colspan="2">
<input type="submit" name="submit" value="Submit"/>
</td>
</tr>
</table>
</form>
When you reload the page, $rndnum1 and $rndnum2 are set to new random numbers via the rand() function. That's why they are not staying the same. Try passing the original random numbers along with the POST, and calculate the numbers from $_POST before checking if the answer's correct.
To do this, make sure you include the following line for both random variables in your submission form:
<input type="hidden" name="rndnum1" value="<?php echo $rndnum1 ?>" />
Then, on the next load of the page after the answer form is submitted, get the numbers with $_POST['rndnum1'], etc.
Include the generated random numbers in hidden form fields so they're submitted to the server.
For example, just inside <form>:
<input type="hidden" name="rand1" value="<?=$rndnum1?>">
<input type="hidden" name="rand2" value="<?=$rndnum2?>">
Then in PHP, when you're processing the form, use $_POST['rand1'] and $_POST['rand2'] to retreive the original numbers, multiply, then compare with the user's given answer.
add srand(0) to top of your code.
actually to you may want to use a cookie that is randomly initialised, and then pass that to srand()
Something like this should work.
<?php
#session_start();
if($_SERVER["REQUEST_METHOD"] == "GET")
{
$answer=0;
}
if (!$_POST['submit'])
{
$_SESSION['rndnum1'] = rand(1, 12);
$_SESSION['rndnum2'] = rand(1, 12);
}
else
if($_SERVER["REQUEST_METHOD"] == "POST")
{
$answer = trim($_POST["answerInput"]);
$check = $_SESSION['rndnum1']*$_SESSION['rndnum2'];
if( $answer == $check)
{
$msg = "Correct!";
}
else
{
$msg = "Wrong!";
}
}
echo "<h3>". $_SESSION['rndnum1'] . " x " . $_SESSION['rndnum2'] . "</h3>";
if ($_POST['submit'])
{
echo $msg;
}
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" >
<table>
<tr>
<td>
First Name:
</td>
<td>
<input type="text" name="answerInput" value="<?php echo $answer; ?>" size="20"/>
</td>
<td>
<?php echo $answerError; ?>
</td>
</tr>
<tr>
<td class="signupTd" colspan="2">
<input type="submit" name="submit" value="Submit"/>
</td>
</tr>
</table>
</form>

Categories