0

I am creating a webstore. I am using PHP sessions to navigate to the next page.

what the program should do is: when I click on a specific image, then the sessions variables should be assigned accordingly based upon the image clicked, but the problem is all session variables are assigning without clicking.

This is my code:

<div class="col-sm-3 col-xs-6"  style="text-align:center">
<a href="list.php"    onclick="<?php $_SESSION['x'] = 'clothing'; $_SESSION['v1'] = 'shirts';?>" ><img class="img-responsive  img-circle " src="image/0.jpg" />Clothing</a>
</div>
<div class="col-sm-3 col-xs-6" style="text-align:center" >
<a href="list.php"   onclick=" <?php $_SESSION['v1'] = 'mobiles'; ?>" ><img class="img-responsive img-circle " src="image/5.jpg"  />mobiles</a>
</div>

So without clicking, mobile session variables were assigned to "mobiles" as it is the last declared...

ndm
  • 59,784
  • 9
  • 71
  • 110

1 Answers1

1

PHP code gets executed before that page is send to the broser. So your code looks like this when it gets to the browser:

<div class="col-sm-3 col-xs-6"  style="text-align:center">
    <a href="list.php"    onclick="" ><img class="img-responsive  img-circle " src="image/0.jpg" />Clothing</a>
</div>
<div class="col-sm-3 col-xs-6" style="text-align:center" >
    <a href="list.php"   onclick="" ><img class="img-responsive img-circle " src="image/5.jpg"  />mobiles</a>
</div>

And the session variables are set, like you said.

You cannot set php variables in html (or execute any other php code). What you can do is: if the user clicks on the image send a request to the server which then sets the session variable the way you want to.

I guess the easiest way to achiev what you want to do is by addin parameters to the link:

<div class="col-sm-3 col-xs-6"  style="text-align:center">
    <a href="list.php?x=clothing"><img class="img-responsive  img-circle " src="image/0.jpg" />Clothing</a>
</div>
<div class="col-sm-3 col-xs-6" style="text-align:center" >
    <a href="list.php?v1=mobiles"><img class="img-responsive img-circle " src="image/5.jpg"  />mobiles</a>
</div>

In your list.php you can get all the params via the $_GET variable.

Edit: just to make clear that my suggested solution does not sent a request to the server just to set the session variable, but instead gives the information to the list.php where it can be used to set the session variable.

A.L.
  • 129
  • 1
  • 7