passing id of an image to another page - php

This might a little noobish but I don't know where to start with my problem. A friendly nudge in the right direction would be greatly appreciated.
I am trying to have a gallery of material, the images of the materials are stored in a database, now i want to make the users click on a specific image of the material that they like, this would lead them to next page that would calculate the price.
So i guess my question is, how do i carry this variable of their choice to the next page from the gallery?
Any help greatly appreciated
btw this is my code for getting the images displayed from the database:
<?php
mysql_connect("localhost","root","");
mysql_select_db ("imagez");
$res=mysql_query("select * from imgz");
while($row=mysql_fetch_array($res))
{
echo "<a href=\"page.php?id={$row['id']}\" />
<img src=\"{$row['img']}\> </a>";
}
?>

you can hand over values to another page by...
(1) QUERYSTRING (URL)
page.php?do=show&id=5
create those by pulling the unique id of a record from your db and create a link:
echo "<a href=\"page.php?id={$row['id']}\" />{$row['name']}</a>";
assuming that your table imgz has the fields id, name.
in page.php, you get those variables with
$_GET['do']; $_GET['id'];
pro: quick & easy
contra: can be easily manipulated by evil users - they change the querystring and get your script to do weird things.
(2) POST
create a <form method="post" action="page.php">with a hidden field named id containing the 'id' you want to pass. Add a <submit>-button to send the data to page.php.
in page.php, you get those values by:
$_POST['id'];
pro: safe, because evil user can't fiddle with POST
contra: overhead
(3) SESSION:
call session_start(); on top of every page, write your data into the session by...
$_SESSION['id'] = $id; $_SESSION['do'] = "show";
these variables will be kept between pages, in page.php you can simply use S_SESSION['id'] and have that value - if you called session_start().
pro: easy and safe, PHP will do the work for you (e.g. handling cookies etc.)
contra: will put load on your webserver if traffic goes up on your site.

You can set URL parameters, so when they click it, you would have a parameter like;
http://example.com/pricecheck.php?photoid=435
Then on the page you would do;
$photo = $_GET['photoid'];
Then you would have the ID of that photo on the page

Instead of passing the variable via URL, you can use cookie to store the variable and doing the calculation to check up.
<?php
$expire=time()+60*60*24*30;
setcookie("price", "$54", $expire);
echo $_COOKIE['price'];
?>
Now that variable $price would be available for each your webpages, and finally don't forget to clear the cookie `setcookie("hp","", $expire);

Related

Carrying Variables Between 3 PHP Pages

I am creating a set of 3 pages, each with a dropdown menu. The values from the previous dropdown menus will populate the next dropdown menu. I understand that I must use session variables to hold the value of each dropdown menu into later pages. As a simple test, I echo the variables to see if they have been carried over -- and that's where the problem is.
I have three different files: choose_cc.php, choose_uni.php, and choose_major.php
The value from the dropdowm menu in choose_cc.php does get echoed in choose_uni.php -- however the value from choose_cc.php does NOT get carried over into choose_major.php -- despite me storing it into a session variable.
the flow of pages is like this;
choose_cc.php --> choose_uni.php --> choose_major.php
Each php file has it's own form. The problem lies in when I try to call the value from choose_cc.php into choose_major.php, i have issues.
The name of the form on choose_cc.php is choose_cc.
The name of the form on choose_uni.php is choose_uni.
So for example, in choose_uni.php, I retrieve the value from the dropdown menu on the previous page (choose_cc.php) like this:
$_SESSION['choose_cc'] = trim($_GET['choose_cc']); //fetches cc from previous page
$user_cc = $_SESSION['choose_cc'];
echo $user_cc;
and when I echo it as I did above, it works! Okay perfect!
But when I head onto choose_major.php, I try retrieving the value again from the form, but to no avail like this;
echo $_SESSION['choose_uni']; //this works
echo $_SESSION['choose_cc']; //this doesn't work
I have made sure to store to do session_start() on the beginning of each page as well.
Please help me out! this is driving me insane!
Create a new "see.php" with this:
session_start();
print_r($_SESSION);
and execute it after each choose_cc.php, choose_uni.php and choose_major.php to take a look the session you have after you run your programs.
Simple as this:
a) add session_start(); at the beginning of ALL the involved pages. Some weird stuff happens sometimes if you put a space before it, or even a new line. So be sure it is the very first thing in your script.
<?php
session_start();
?>
b) if needed, check the variable to save into session for not empty(); That way you can be sure the session variable contains something, unless of course you want explicitly to be empty.
c) then load the session variable. You can temporary check it with a var_dump();
<?php
session_start();
if (!empty(trim($_GET['choose_cc'])))
{
$_SESSION['choose_cc'] = $_GET['choose_cc'];
}
var_dump($_SESSION['choose_cc']);
?>

PHP How to stay on same page after another form has been processed?

So on this application I'm working on, it searches for some code in my database, grabs it, opens a new page and places the code (where necessary) onto the new page by getting its id.
Now within that code (from the database) there is another form that is processed based on user's input. The problem that I am getting is that the new form is not processed on the same page. It redirects to a new url that doesn't specify the code from the database. For example...
When the new page is generated with the code from the database, the url looks like this...
localhost/newpage.php?id=1
Then when I submit the form within the code from the database it changes to this...
localhost/newpage.php?input1=blah&input2=blah
But I want something like this...
localhost/newpage.php?id=1&input1=blah&input2=blah
Just FYI this code needs to be dynamic. For example, let's say I don't know what id the user is looking for and within that id I don't know how many input fields there are.
If you guys need some explicit code (obviously I left out the unnecessary things)...
This is searchpage.php which searches db and displays all relevant items. Then the user selects an item which contains an id and generates newpage.php with that id...
//there is a search query then puts all elements in an associative array
$rows = items->fetch_all(MYSQL_ASSOC);
foreach ($rows as $row) {
$id = $row['id'];
echo "<a href='newpage.php?id=$id>User clicks to generate a newpage</a>";
}
This is the form retrieved from database and placed in newpage.php...
<form action="newpage.php" method="GET">
<input name="input1"></input>
//there can be an x amount of input tags here depending on what id is pulled
</form>
This is the php at the top of newpage.php when it is generated...
if (isset($_GET['id'])) {
//retrieves data from specified id from database
if(isset($_GET['inputs'])) {
//do something with user inputs
}
}
Is there any way to achieve this? All help is appreciated! Thanks :)
SOLUTION
For this to work, I had to create a session which stores the id. Consequently i had to change all my $_GET varaibles (that dealt with id info) to $_SESSION variables. But it works as long as you're not storing critical/sensitive info!
Here's the code changes...
Changes in search.php ...
//there is a search query then puts all elements in an associative array
$rows = items->fetch_all(MYSQL_ASSOC);
foreach ($rows as $row) {
$id = $row['id'];
$_SESSION['current_id'] = $id;
echo "<a href='newpage.php?id=$id>User clicks to generate a newpage</a>";
}
Changes in newpage.php ...
<form action="newpage.php?id=" method="POST">
<input name="input1"></input>
//there can be an x amount of input tags here depending on what id is pulled
</form>
Changes in php of newpage.php ...
if (isset($_SESSION['current_id'])) {
//retrieves data from specified id from database
if(isset($_POST['inputs'])) {
//do something with user inputs
}
}
ALL THANKS TO...
Sathik Khan
You can get the query string "id" in referred header. Either you can attach that query string in client or in server.
Please use $_SERVER['HTTP_REFERER'] to get referer url and from there you can get the id. If it's id of logged in user, I would recommend store them in session for security reason.
Based on your comments,
You can take any one of these actions,
1. Keep the ID in your form as hidden variable
2. Update your url with id as one of the query string and send back to client for error correction.
3. Keep the ID in session, if applicable
4. Use post and perform form validation before redirecting
Thanks.

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.

Like/Dislike system like FB

I have my tables set and the design I wanted...the only thing in my way of creating a sexy like/dislike system for my site is the actual PHP it would take (dont worry i wrote a bunmch of the code, its just not sending)
My problem is that my code isnt sending to any of the tables, so my question to you is how would I actually get it to send to the db?
Here's the code I have in place so far (along with the button)
Button
<form action="up.php">
<input type="image" value="upBtn" name="upBtn" id="upBtn" src="images/add.png"> Like
</form>
Actual code (up.php)
<?php
require 'connect2.php';
if (isset($_POST['upBtn'])) {
mysql_query("INSERT INTO votes (id, user, upvote, downvote) VALUES ('', '$username', '+ 1', '+ 0')");
mysql_query("UPDATE searchengine SET rel = rel '+ 1' WHERE id = '$id'");
}
?>
$user name def (on the top of the page all of this code is on)
if (isset($_SESSION['id'])) {
$userid = $_SESSION['id'];
$username = $_SESSION['username'];
$id was already defined on the page since all of this is on the page I wanted the votes to appear
You should include the "id" as a hidden field in the form, as the id in the session may not be the id they are voting one, for instance, if they opened another post in a separate tab, and then voted on one that had been loaded before. Also, are you sure the session variables are being saved correctly? Depending on your PHP configuration, sessions are not started by default, in order to conserve resources, and you have to call session_start() at the top of each page to actually start the session.
Try adding method="post" to the form tag. If it still doesn't work, you should put some debugging code inside the if statement to see if your queries are actually being run.

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