No $_GET = empty($_GET)? - php

I have a paginated table of names and ages that I want to filter by the "name" field.
For that I have an input called "name".
<input type="text" name="name" value="<?php echo $_SESSION['name']; ?>">
While switching between pages, in order to not carry around the filter in the url in the form of:
table.php?name=John&page=3
i am saving the $_GET['name'] to a $_SESSION['name'] and then apply that session to the SQL query string.
$_GET['name'] ? $_SESSION['name']=$_GET['name'] : null;
I would like to be able to clear the filter by having the user deleting the content from the input and pressing enter.
I have tried:
if($_GET['name']=="")
unset($_SESSION['name']);
The problem is that when I switch page and use the link:
table.php?page=7
it resets $_SESSION['name'] and takes me back to the selected page of the unfiltered table.
Any ideas on how I can work around this issue?
Many thanks in advance.

I think your problem is in your ternary operation. At first dont use this operation if you don't understand his logic. Ternary operation can reduce the amount of code, but in the same time can confuse you very much.
So:
$_SESSION['name'] = $_GET['name'] ? $_GET['name'] : null;

I managed to work around the issue by repacing
if($_GET['name']=="")
unset($_SESSION['name']);
with
if(isset($_GET['name']) and $_GET['name']=="")
unset($_SESSION['name']);
the isset() made all the difference.
Now it will properly check if an empty value is being passed in the $_GET['name'] and proceed with the IF accordingly.
Many thanks all of you for all your assistance.

Related

How can i use variable on the previous page

I have a form for search user on like index.php?topic=pagename
I assign to variable what i wrote search form. So like ;
$name= $_POST['username'];
Everything okay, i can run this query on same page.
But i want to add new query under the previous query's result.
So like ;
$name have 5 euro.
Add money : NEW FORM
I can add form for add new money to under the previous query echo's. It seems. And it runs but i cant use previous variable $name .
Btw, add money form run on same page
What about just storing that value in a hidden input in the new form?
// new form
<input type="hidden" name="name" value="<?= $name ?>"/>
You can try $_SESSION:
http://php.net/manual/en/features.sessions.php
or $_COOKIE:
http://php.net/manual/en/features.cookies.php
Use sessions for this.
Store data in session, then use it in previous page.
http://www.w3schools.com/php/php_sessions.asp

Keeping some selected options after submitting form

Thanks in advance for any suggestions on the following:
I've created a php-page to add works from composers to CDs in a database. It's a combination of two forms and looks like this:
1st form:
Composer : [drop down list] : Select
Some blank space
2nd form:
Title : [drop down list]
Track number : [empty varchar field]
Work : [drop down list]
some other fields
Process button
After selecting a name in the first block (posting to $_SERVER["PHP_SELF"]) I stay on the same page, that name is shown in the blank space in between and the drop down lists are populated with only CD titles and works of the selected composer.
I can then select from the lists and enter other data in the other fields. Hitting the process button posts the data from the second block to another page which will eventually send everything to a table in a MySQL database.
After that I send myself back to the first page with header("Location: the_first_page.php")
So far so good, but upon returning I would like the composer, title and work to be preselected. Now I'm sent to a blank page and have to start from scratch. I think I've seen some solution involving testing $_POST['something'] against <option value> in a drop down list but I can't seem to make that work.
My question is: Is there a way to send $_POST['Title'] and $_POST['Work'] back to the first page somehow? Or is it better to split the two forms over seperate pages?
All help is welcome.
You could use sessions or the post data itself. For using the post data itself, the page where you send the request should be the same and include the script that will process it if there's some data like this:
if (!empty($_POST)) {
include "save.php";
}
// More code...
?>
<select name = "a">
<option <?php if ($_POST['a'] == "test") echo "selected"; ?> value = "test">
<option <?php if ($_POST['a'] == "testb") echo "selected"; ?> value = "testb">
</select>
Of course there are many more ways, but this is just a simple one to get you started. Things to know: you might want to change the variable $_POST and clean it up before using it. In this case it should be fine, but in <input type = "text" value = "<?= $_POST['b']; ?> name = "b">` you have a serious security issue.
For sanitizing the input, you want to sanitize it respect to what you expect. But also, as an EXTRA meassure, you normally want to strip everything that looks like a <script>, onclick ="", ' DROP TABLE users and similar. It's not an easy subject, so I recommend you reading on it, mainly on the XSS attacks which is relevant to showing the text back to the user. While it might seem too much work for this "simple case", it is useful in many more situations.
Use session variables and put conditions for them ... see [ $_SESSION ].

Passing variable from first page to third page PHP

I have a drop down list on page one with select code:
print "Select week for season 1: <select name='Week_select'> <br>";
On page 2 I have
$varWeek=$_POST['Week_select'];
Then another drop down list:
print "Select a team that played season 1and week $varWeek: <select name='Team_select'><br>";
So far so good and many thanks to all who have gotten me this far.
Now when I go to page 3, I lose $varWeek
I see that I should either use a $_GET or pass it as hidden.
I tried $varWeek=$_GET['Week_select'];
but that didn't work.
I am unsure how to pass it hidden. Please help me understand a little more.
Many thanks in advance
A better approach would be to register those variables as session variables. This way they won't show up in the URL and you will be able to access them across several pages. Have a read here:
http://www.php.net/manual/en/intro.session.php
You can access/store a session variable like this:
$_SESSION['varname'] = 'value';
and on another page
var_dump($_SESSION['varname']);
Add the variable into the form, like you said, as a hidden field, like so:
print '<input type="hidden" name="Week_select" value="'. $_GET['Week_select'] .'" />';
Then on the page which handles the form, the variable will be available in $_POST['Week_select']

Saving page ID within $_SESSION

I am new to sessions, and think I get the basics of them, they seem to act like containers holding information which you can use on at a later stage and are linked to your UID.
I am wondering how I would save the ID of a page (example ID123) on the click of a button, and what exact code I'd have in the header.
Much appreciated in advance!
EDIT:
This is on wordpress, sorry to add this, each page has an 'event ID' I want this to be stored for use later (at a kind of checkout page) sorry for not adding this!
Saving page ID within $_SESSION
session_start();
$_SESSION['pageId'] = (int) $_GET['ID'];
Now you can use $_SESSION['pageId'] to get its value where you need.
Make sure to put session_start(); at top of your script where you use session-related functions or $_SESSION array.
To unset it when you don't need it anymore, you would do:
unset($_SESSION['pageId']);
session_destroy();
session_regenerate_id();
update
On button click you would do something like this:
var btn = document.getElementById('btnId');
btn.onClick = function() {
window.location = 'saveSession.php?id=xxx' // replace xxx with your id value
};
Now in saveSession.php you wll have to use code like shown above for storing it in session.
You can also use Ajax though.
In wordpress you cannot pass custom url parameters. So you cannot send something like
http://yourwordpresswebsite.com/?custom_param='value'
WOrdpress doesnt allow it. SO if all you want is a Post ID or a Page ID. It is easy to grab in wordpress. Do:
$val= $post->ID
Thats it and $val is set. The way I do if I have to send any custom parameters to a different file is by sending it as a form variable. There might be better ways but I am new to Wordpress and php too. So this is what I do:
<?php
echo "<form action='php_file.php' method='post' name='form_name'>
<input type='hidden' name='eventid' value='$event_id' />
<input type='submit' name='submit' value='submit'/>
</form>";
?>
If you want this to be your session info you can just add it in your php file where you are collecting the above fields.
session_start();
$_SESSION['pageId'] = (int) $_GET['eventid'];
/* Do not forget to check if the get variable is clean before you perform any operations, use mysql_real_escape_string(). It is a very important security measure. */
This might not be the best approach as I told you I am new to wordpress too.

Storing redirect URL for later use

I'm trying to store the redirect URL for use a few pages later but I'm having trouble figuring out how to get it from one place to another.
Usually I'd just pass a variable thru the URL, but since my redirect URL contains URL variables itself, this doesn't exactly work.
To give you a better idea of what I'm trying to do, here's the structure.
PAGE 1: User can click a link to add content on PAGE 2
PAGE 2: User enters text. Submitting the form on this page calls "formsubmit.php" where the MySQL data entries are handled. At the end of this I need to redirect the user to PAGE 1 again. The redirect URL needs to exactly match what was originally on PAGE 1
Does anyone have any suggestions on how to go about this?
You should use $_SESSION to store the variable in session memory. As far as specifics go with how to handle this in particular, you should be able to figure it out (store the variable, check if it exists later, if so redirect etc etc) but $_SESSION is going to be much more efficient / less messy than trying to pass things back and forth in query strings.
To declare a session variable you would do something like this:
$_SESSION['redirUrl'] = "http://www.lolthisisaurl.com/lolagain";
And then to reference it you just do
$theUrl = $_SESSION['redirUrl'];
Here is some material to get you started: http://php.net/manual/en/reserved.variables.session.php
I would recommend either using session variables, or storing the redirect url in a hidden form parameter. Session variables are pretty simple; just initialize the session (once, at the top of each page), and then assign variables to the $_SESSION global var:
<?php
session_start();
...
$_SESSION['redirect_url'] = whatever.com;
...
Hidden form parameters work by sending the data from page to page as form data. On the backend, you would add code that would put the URL to be stored in a form variable:
<input type='hidden' name='redirect_url' value='<?php echo $redirect_url; ?>';
On each page, you can take the URL out of the $_POST or $_GET variable (whichever is appropriate) and insert it into a hidden form in the next page.
You can use urlencode and urldecode to pass a string that contains elements that would otherwise break a url in a url query.
I can see two possible solutions :
get the previous page from document.referrer ([edit] find more info on this SO thread : getting last page URL from history object - cross browser?)
store the previous url via a session variable ([edit] MoarCodePlz pointed this out in his answer)
Regards,
Max
You can add this hidden field in to your form:
<input type="hidden" name="referer" value="<?php echo $_SERVER['HTTP_REFERER']; ?>">
Then use header() to redirect to this page:
header('Location: '. $_POST['referer']);

Categories