i have a php page,
on that page i have text boxes and a submit button,
this button runs php in a section:
if(isset($_POST['Add'])){code}
This works fine here and in that section $name,$base,$location etc are calculated and used. but that section of code generates another submit button that drives another section of code.
it is in this second section of code that i wish to add data to the DB.
Now i already know how to do this, the problem is that the variables $name and so forth have a value of NULL at this point.. but they can only be called after the first code section has been run where they gain value.
How do i maintain these values until the point where i add them?
Resources:
the page feel free to try it out:
location mustbe of the form 'DNN:NN:NN:NN' where D is "D" and N is a 0-9 integer
http://www.teamdelta.byethost12.com/postroute.php
the code of the php file as a text file!
http://www.teamdelta.byethost12.com/postroute.php
lines 116 and 149 are the start of the 2 button run sections!
I think you are looking for PHP's session handling stuff ...
As an example, first page:
session_start(); # start session handling.
$_SESSION['test']='hello world';
exit();
second page:
session_start(); # start session handling again.
echo $_SESSION['test']; # prints out 'hello world'
Behind the scenes, php has set a cookie in the users browser when you first call session start, serialized the $_SESSION array to disk at the end of execution, and then when it receives the cookie back on the next page request, it matches the serialised data and loads it back as the $_SESSION array when you call session_start();
Full details on the session handling stuff:
http://uk.php.net/manual/en/book.session.php
Around the add-button you are creating a second form. If you want to have the data within this form then you will have to create hidden input fields. Because you are sending a second form here. Or you are moving the add button up to the other form.
Or as others are mentioning.. Save the values into a session.
you could store them in a session
// first part of form, store name in session
$_SESSION['name'] = $_POST['name'];
// 2nd part of form, store in database
$name = mysql_real_escape_string($_SESSION['name']);
$sql = "INSERT INTO table (name_column) VALUES ('$name');
You can also try using hidden forms variables to store the data
Related
I currently have some php code on a form action, and it is being updated to the form's next page with
<?php echo $_POST['var here']; ?>
and it is working, but I noticed when Im trying to refresh the page it asks to confirm resubmission. When I resubmit it works in that tab in which it was sumbitted, but in another new tab it does not show the displayed php post variables. I even took it the next step by seeing that when I open the 2nd page after the form action has been submitted the php post variables are gone...
Help!
Thanks!
When you submit a form with <form method="post" /> it does a post request to the server, thus populating $_POST. When you open the link in a new tab it is no longer a post request but a get request. That is why you'll see nothing in $_POST.
$_POST — usually from forms
$_GET - from values on the URL (the query string myscript.php?myvar=Joe)
You can find plenty of resource about it. You can start here
If you want to keep the values you can save them to the session:
<?php
session_start(); // should be at the top of your php
if (isset($_POST['var'])) {
$_SESSION['var'] = $_POST['var'];
}
$myvar = isset($_SESSION['var']) ? $_SESSION['var'] : "no var";
echo $myvar;
Now the value is stored in the session so you can visit the page in a new tab and it will still be there.
This sounds like desired behavior. The $_POST variable should only be filled when the post action is created. If you're looking to store variables across pages you could store it in either the $_SESSION var in PHP or deal with the front end $_COOKIE business. If you're always going to be rendering pages from the backend then $_SESSION is the way to go. It's never too late to read up on cookies and sessions.
The skinny of it is that you're going to want to do something like this:
<?php
session_start();
if ($_POST['var']) {
$_SESSION['var'] = $_POST['var'];
}
echo $_SESSION['var'] ?: $defaultValue;
Then you'll notice that the message changes only when you post and won't exist before then.
I have three forms - payment.php , payment1.php and paydb.php . payment.php contains the front end form.payment1.php contains the back end of the form of payment.php. whereas we are shifting to paydb.php from payment1.php. Now I'm filling the form by entering member number in payment.php which is retrieved in a variable $member_no in payment1.php .Now I want to get the value of member_no in paydb.php . How to do that ?
After receiving $member_no in payment1.php redirect to paybd.php with a get array
using
header('Location: http://www.example.com/paydb.php?member_no=$member_no');
then receive $_GET['member_no'] number and assign to a variable
example:
$member_no = $_GET['member_no']
The first thing is make sure you are not passing sensitive information where the public can see it. Such as in a URL.
As soon as you get the member's number... store it in a session variable.
You can probably do this when they log in.
session_start();
$_SESSION['member_no'] = $member_no;
OR on the first payment page (assuming 'member_no' is the name of the form element being passed) like this...
$_SESSION['member_no'] = $_POST['member_no'];
Now that session will persist as long as the visitor has their browser open and you don't have to worry about passing it from page to page.
You can use that session on any subsequent page simply by calling it.
<?php echo $_SESSION['member_no'] ?>
Without showing this information to the public.
ALWAYS make sure you place this at the top of any page where you want to use session variables.
if (!isset($_SESSION)) {
session_start();
}
<!doctype html>
<html>
<head>
<title>Index</title>
</head>
<form action="newquestion.php" method="post">
Question <input type="text" name="question">
<input type="submit">
</form>
<body>
</body>
</html>
PHP file...
<?php
static $q = 1;
echo $q;
$q++;
?>
I'm new in PHP. Will this not increment $q by 1 each time "newquestion.php" is called? if not how to increment this variable each time this page(newquestion.php) gets called or opened?
No, because $q resets to 1 each time the page is called. You need some sort of persistence strategy (database, writing to a text file, etc) in order to keep track of the page views.
It's also a good idea to consolidate this functionality into a class, which can be used across your code base. For example:
class VisiterCounter {
public static function incrementPageVisits($page){
/*!
* Beyond the scope of this question, but would
* probably involve updating a DB table or
* writing to a text file
*/
echo "incrementing count for ", $page;
}
}
And then in newquestion.php,
VisiterCounter::incrementPageVisits('newquestion.php');
Or, if you had a front controller that handled all of the requests in your web application:
VisiterCounter::incrementPageVisits($_SERVER['REQUEST_URI']);
Every php script inside in a page is executed when you are loading this page. So everytime your script is executes line by line. You can not count page loading number by the process you are trying.
you can follow one of the process below:
1) you can save it to the database and each time when it is loading you can execute query to increment the count value.
2) you can do it by session like this:
session_start();
if(isset($_SESSION['view']))
{
$_SESSION['view']=$_SESSION['view']+1;
}
else
{
$_SESSION['view']=1;
}
The easy way is using a SESSION or a COOKIE based persistence methodology.
Using SESSION example:
In the beggining of the page (firt line prefered) put the following code:
session_start();
Check if a session for this user has been created and recorded, if so, increment by one the value of q session variable and display it.
If not, initialize q session variable with value 1, store and display.
if(!isset($_SESSION["q"]) //check if the array index "q" exists
$_SESSION["q"] = 1; //index "q" dosen't exists, so create it with inital value (in this case: 1)
else
$_SESSION["q"]++; //index "q" exists, so increment in one its value.
$q = $_SESSION["q"]; //here you have the final value of "q" already incremented or with default value 1.
//doSomethingWith($q);
Using COOKIE example:
$q = 0; //Initialize variable q with value 0
if(isset($_COOKIE["q"])) //check if the cookie "q" exists
$q = $_COOKIE["q"]; //if so, override the q value 0 with the value in the cookie
$q++; //increment in one the q value.
setcookie("q",$q); //send a HTTP response header to the browser saving the cookie with new value
//doSomethingWith($q);
//here you have the final value of "q" already incremented or with value 1 like in session.
With cookies, you cannot use $_COOKIE["index"] = value for set a value for cookie, you must use setcookie instead for that. $_COOKIE["index"] is only for read the cookie value (if it exists).
SESSION still use cookie, but only for identify that user is the owner of that session, the user cannot change the value of session directly (only if you provide a way to they do that).
Using COOKIE the user will see a cookie with name "q" and it's value and can easily change the value through simple javascript code, browser tools (like Google Chrome Developer Console Tool) or any extension for Browser (Edit This Cookie, a Google Chrome extension that list all cookies, values and parameters for a webpage).
Remeber that any session_start call (only one per page is necessary) or setcookie calls must be made before any buffer output like (but not just) echo, print. Because both calls produces a HTTP Header "Set-Cookie" and HTTP Headers must be sent before content body, calling this methods after a buffer flushing will throw a exception.
The two examples above are per user count. If you need a per application or per page count, you must implement a custom counter system, using file system to store data (the pageviews/page requests) or database to track individuals request (with date, ip address, page url, page name, anything else).
It won't work as you think. PHP code is executed each time from start to finish - meaning that no variables are kept over from one run to the next.
To get around this, you could use a session variable (this is a special sort of variable) which will keep a value in it that you could keep for each visitor to the site. This will however work for EACH VISITOR individually.
If you want to increment the value for all users (you open the first one, it says 1, I open the second it says 2 and so on) you will need to either store it in a database (good option), write it out to a text file (not really a good option) or magic up some other way to keep it saved.
Put $q initialization in any of your init page then increment the value.
or put the variable to increment in the session. with that, you could at least see, how often one user calls your pages.
The problem with your code is that the variable is first set to 1 each and everytime the page is visited. You will have to make use of $_SESSION. But then again the problem with using session variable would be that if you are trying to increase the value of your variable from different PCs or different systems, session would not work. For this the best thing will be to insert the value in database.
I have a login form which sends 3 post values from username, password and submit button. But my form processor has 3 pages one is validation.php which validates the field second is read.php which checks the posted values against db and third is login.php which is a result of login success. All redirect to each other respectively on success. Problem here is that when I try to access the user posted values from form in read.php (redirected page) not validate.php (action page) I get an error of undefined index.
I really don't see why you are doing all those redirects, but if you want to make the data more persistent you could use a session variable, because the $_POST superglobal is only set for the current request.
firstfile.php
<?php
session_start();
$_SESSION['posted_data'] = $_POST;
other file
<?php
session_start();
var_dump($_SESSION['posted_data']);
However as already stated you may really want to reconsider doing all the requests.
UPDATE
Besides the fact that you will loose your data you are also doing multiple (unneeded) requests to simply sumbit the form. The only redirect that should happen is to the successpage when you have done all you work. See this for more information: http://en.wikipedia.org/wiki/Post/Redirect/Get
If you are look to keep you code clean you could always just include the other files or go for an OOP approach.
You should do one page only that will do all the work. That doesn't seem too complicated of a script, so I would advise putting everthing together on one page.
You did not provide any code so I'll show you a general example. I just typed it without rereading so it's not pure PHP syntax, just the spirit:
<?php
$login=$_POST['login'];
$pwd=$_POST['pwd'];
$dbcheck = mysql_fetch_array(mysql_query("SELECT COUNT(1) FROM table WHERE user =$login and pwd = $pwd"))
if($dbcheck[0] > 0) {
//Login success
//Setup your session variables, cookies, etc
//Then you can do your redirect here
} else {
//Page for wrong login
}
acitvity.php
//Form start
<form action=''>
</form>
//Form End
//Get POST Values
<?php
$_POST[''];
?>
//End
if i refresh the page after form is submitted, all the posted values are resubmitted, reason because all values are in browser so they are resubmitted. When i was searching solution for this, i got info that if the form & post operation done in separate php file then no more issue in posting values on refresh.
Is this the solutions? but now i have to do both in single file & POST values should not be submitted again on refresh.. is there any way to do this???
Learn PRG Pattern so that you can do this properly :)
http://en.wikipedia.org/wiki/Post/Redirect/Get
For example, you are trying to handle a user registration form, so what you do is you get a bunch of POSTed values, and save it into your database.
if(!empty($_POST)) {
// validate and save to db
// get last inserted user_id
}
After you do that, instead of returning the same page with the previously POSTed values, you redirect the new user, for example to his profile page (assuming you have no activation requirement in place)
if(!empty($_POST)) {
// validate and save to db
// get last inserted user_id, say in $user_id
header("Location: /users/$user_id");
}
That way, the browser redirects and you won't have problem with say, double registration, whenever the user hits refresh.
After saving to your database, reload your page:
if ($_POST) {
// Save $_POST to database and other stuffs
// Reload current page to discard $_POST
header('Location: my_page.php');
}
That's called PRG or Post/Reload/Get
You can use unset($var) to unset a variable. However, I think the issue is with the browsers; some of them try to be smart and will remember form data regardless when you refresh the page. If you hit "go" or "enter" on the URL bar it does a "true" refresh though.