Why session value in php keep incrementing every time the page refreshed - php

I am new to PHP and I am using session variables to create shopping cart, as I need to increment the number of items in the cart, I use session variables. However, this variable keep increment every time the page refreshed/reload, which increment the number of items.
<?php
session_start();
if (!isset($_SESSION['items'])){
$_SESSION['items'] = 0;
}
function increament_items(){
$_SESSION['items']++;
}
?>
and in HTML I have this
<a id="laptop" href="index.php" onclick="<?php increament_items() ?>",title="header=[Add to cart] body=[ ] fade=[on]">
I have tried to use form using post/get and still the same.
any help?
thanks

Php, as it is not a client language, will not work "onclick", but every time the code
<a id="laptop" href="index.php" onclick="<?php increament_items() ?>",title="header=[Add to cart] body=[ ] fade=[on]">
Is loaded.
So, you could use something like this to solve your problem.
1) Add at the end of your php code this:
if($_GET['add']==1){
increament_items();
}
2a) Then, replace your html code with this one
<a id="laptop" href="nameofyourphppage.php?add=1">Add</a>
2b) Or, if you prefer, after having included jquery library (*) into html page, use the following one:
<script>
function openLink(url)
{$("#add").html('Loading...');
$("#add").load(url, function (responseText, textStatus, req) {
if (textStatus == "error") {
$("#add").html('An error occurred');
}
});
}
</script>
<a id="laptop" href="javascript:openLink('nameofyourphppage.php?add=1')">Add</a>
<div id="add"></div>
The second solution will run the php code without the user leaving the html page.
(*)To include the jquery library, put into the head section of your html page this code:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

Related

Pass data from php mysql to pop up on same page

I have a link in a php while loop
echo "<a href = '#$product_id' onclick = 'pop_up()' id = 'linker'>See more</a>";
The pop up requires the product id to search the database but hash tag is client side. I tried to use javascript window.location.hash but the outcome was not very reliable.
Does anyone know a method preferably server side I could use to retain the active product id while I call the pop up, attain the product id, use it to query the database and output it in the pop up.
I have a session already started and tied to a different condition.
I tried to call the product id directly from the pop up but because of the loop I only get either the first or last in the array.
<?
while ($i < $num) {
$product_id=mysql_result($result,$i,"prod_id");
$title=mysql_result($result,$i,"lTitle");
//main page
echo "<b>" , $title;
echo "<a href = '#$product_id' onclick = 'pop_up()' id = 'linker'>See more</a>";
?>
<!------pop up--------->
<script type="text/javascript">
function pop_up(){
document.getElementById('pop').style.display='block';
}
</script>
<div id="pop">
<p style='color:#6F0A0A; font-size:15px;'><? echo $product_id; ?></p>
</div>
<?
$i++;
}
?>
I'll try answering but to be honest the question is very vague and the code is a bit messy.
First off, you can simply send the product_id as a GET variable to the new popup and read it in PHP. Something like this will work:
echo "<a href = 'http://www.mydomain.com/popup.php?product_id=$product_id' onclick="window.open(this.href, 'popup_win',
'left=100,top=100,width=500,height=500,toolbar=1,resizable=0'); return false;" id = 'linker' >See more</a>";
On your popup.php file (the popup page) you will get the product_id with the PHP $_GET method:
$product_id = $_GET['product_id'];
and then do whatever MySQL query you want, now that you know $product_id.
I hope this helps, if that's not exactly what you meant please add more details so I can revise my answer.
Well, you could first load all this records first and place them into the popup content or, make an ajax request, open the popup, and when the request is done successfully place the values returned into the popup content. Better with JQuery

my php get request doesnt appear in the requested php file

Basically, I am trying to have a user click a button on one php page and it will print a new php page. This function WORKS. The problem is I am trying to have the userID transferred over to the 2nd page and printed on the new page. However, for some reason this seems to be getting lost. When I alert the user# right before the get request is made, the # shows pops up. But when the new page appears in the printer dialog, the userID is missing. Any suggestions would be greatly appreciated.
Function from php page 1:
$("#printing").on('click',function(){
alert (user);
$.get("flyer.php", {userNow: user});
$('body').append('<iframe src="flyer.php?userNow" id="printIFrame" name="printIFrame"></iframe>');
$('#printIFrame').bind('load',
function() {
window.frames['printIFrame'].focus();
window.frames['printIFrame'].print();
}
);
});
php page 2:
<html>
<body>
<div class="wrapper">
<h1>Tai Chi</h1>
<h2>Sign Up Now!</h2>
<h3>Benefits of Tai Chi:</h3>
<ul>
<li>It enhances harmony between body and mind</li>
<li>It improves your internal energy level</li>
<li>Improves your muscle strength and endurance</li>
<li>Reduces back pain</li>
<li>Lowers daily stress</li>
<li>Can slow down the aging process</li>
</ul>
<div id="contact">For more information, please email R-adler#neiu.edu</div>
<div id="userID">
<? echo UserID.$user = $_GET['userNow'] ?>
</div>
</div>
</body>
Try to concatenate the user value like this:
$("#printing").on('click',function(){
alert (user);
$('body').append('<iframe src="flyer.php?userNow='+user+'" id="printIFrame" name="printIFrame"></iframe>');
$('#printIFrame').bind('load',
function() {
window.frames['printIFrame'].focus();
window.frames['printIFrame'].print();
}
);
});
Check also in the url if you get the uservalue passed there.
There is no value being passed in the GET array.
Use the link as flyer.php?userNow="+user

Hide/Show Input's based on mysql data

I have an active session in my page using: $_session_start(); I want to hide part of my form and show another based on the users previous entries.
Basically I offer Direct Deposit and Paper Check I want to be able to have the user only see the fields required for them to complete previously (in signup so the values are already in the database)
Right now the database table is set up like this:
paper_check with a value of 1 (yes pay this way) or 0 (no pay this way)
and the same thing with direct deposit. I need a way to show/hide the fields associated with each based on the users previous selections.
I typed this up but it doesn't seem to do anything. Please help me!!!!! (The class names hide and show are in my css and working properly!)
<?php
if ($_SESSION['direct_deposit'] == 1)
{
$doc->getElementById('check_payable_to')->className+" hide";
}
else
{
$doc->getElementById('name_on_account')->className+" hide";
$doc->getElementById('check_payable_to')->className+" show";
}
?>
I don't see a className property in the PHP DOM library. It looks like this is the way to add a class to an element:
$doc->getElementById('check_payable_to')->setAttribute('class',
$doc->getElementById('check_payable_to')->getAttribute('class') . " hide");
Do you have error reporting enabled? It should be warning about the unknown property.
If you want to do this in Javascript instead of PHP, have your PHP do something like:
<script>
var direct_deposit = <?php echo $_SESSION['direct_deposit']; ?>;
if (direct_deposit == 1) {
/* Do what you want */
} else {
/* Do what else you want */
}
</script>
In your question you said "I have an active session in my page using: $_session_start();" You shouldn't use $_session_start(). It should be session_start() .
className+" hide" should be className .= " hide"
By wrapping each section in it's own div like so:
<div id="paperCheck class="show">
<!--Your Paper Check Information here-->
</div>
<div id="directDeposit" class="show">
<!--Your Direct Deposit Information here-->
</div>
And then by using javascript you are able to do the following:
var direct_deposit = <?php echo $_SESSION['direct_deposit']; ?>;
if (direct_deposit == 1)
{
document.getElementById('paperCheck').className ="hide";
}
else
{
document.getElementById('directDeposit').className ="hide";
}

Issue with Calling JS function through PHP based on IF statement

I have a web based tool. There is a login where username, loggedin and authorised are stored in session variables.
There is one particular page where I have a form that has multiple buttons, I wish to disable one button based on what the users authorisation level is. So if authorised is 0 (user) the button is disabled, else it's enabled as I've only got two authorisation levels, 0 & 1.
I've attached what I've done below, and to me it looks right, obviously it's not!
Here is the JQuery function:
$(function disable(){
$('#signBtn').attr('disabled', true);
});
Here is the PHP code:
if($_SESSION['authorised'] == '0')
{
echo "<SCRIPT LANGUAGE='javascript'>disable();</SCRIPT>";
}
Here is my HTML code:
<input type=\"submit\" name=\"save\" id = \"signBtn\" class = 'eBtnSubmit' value=\"Sign off by Chairperson\" />
If there is anyone out there that can see what my problem is I would really appreciate it...this is my last piece of the puzzle and I'm presenting this today (Software Intern).
So basically if the level is 0 call the function.
Regards,
Gary
No warranty because I don't have all the code
Change the static JavaScript Code to this
var disableSingoff = function () {
$('#signBtn').attr('disabled', true);
}
In your original code, you execute the disable() function right when the DOM is ready by wrapping it in $().
Change the PHP code to this
if($_SESSION['authorised'] == '0') {
echo "<script>$(function () { disableSignoff(); })</script>";
}
It might be easier to simply set the value in the HTML if possible
if($_SESSION['authorised'] == '0'){
echo '<button type="button" disabled="disabled">Click Me!</button>';
}else{
echo '<button type="button">Click Me!</button>';
}
This would work before the page even starts loading.
The other option would be to hook the window on load function.
window.onload = (function(){ [...] }
is the <input type=\"submit\" name=\"save\" id = \"signBtn\" class = 'eBtnSubmit' value=\"Sign off by Chairperson\" /> being echoed from a php statement? if not you can get rid of all the '\'s. they are not necessary when writing strictly html.

php: dynamic link appends content to existing page rather than opening new one

I have a dynamic link which fetches invoice detail based on invoice ID.
<a href='<?php echo $_SERVER['PHP_SELF']; ?>/retrieve?class=InvoiceLineItems&id=<?php echo $invoice['invoice_id']; ?>'><?php echo $invoice['invoice_number']; ?></a> <?php echo $invoice['customer_name'] ?> <?php echo $invoice['invoice_date'] ?>
It calls this function
public function retrieve($class,
$id = NULL)
{
switch ($class) {
case 'Invoice':
$invoices = $this->invoice->getInvoices();
include 'view/invoiceList.php';
break;
case 'InvoiceLineItems':
$partnerInfo = $this->partnerInfo->getPartnerInfo($id);
$invoiceLineItems = $this->invoiceLineItems->getInvoiceLineItems($id);
include 'view/invoice.php';
break;
}
}
However, the include statement found in case 'InvoiceLineItems:' appends the content of invoice.php to the bottom of the existing page rather than replacing it altogether. I've tried adding a target to the anchor, but that didn't work. How do I get the link to open the new page?
UPDATE: based on #sixeightzero suggestion, here is the call to retrieve();
if (isset($_REQUEST['id'])) {
// A request ID value indicates arrival here through link.
$this->retrieve('InvoiceLineItems',
$_REQUEST['id']);
}
Also, I tried using a header redirect.
ob_start();
header('Location: /view/invoice.php', 302);
ob_end_flush();
exit();
It redirects, but I lose access to my array variables from
$invoiceLineItems = $this->invoiceLineItems->getInvoiceLineItems($id);
So, I get errors like
Notice: Undefined variable: partnerInfo in C:\xampp\htdocs\bp\view\invoice.php on line 25
and
Warning: Invalid argument supplied for foreach() in C:\xampp\htdocs\bp\view\invoice.php on line 25
put exit(); at the end of the function to stop executing code after calling it.
or better still use invoice.php to display the invoices instead of the current page.
1) Since, you are using super global *$_SERVER['PHP_SELF']*, the
anchor will always direct to the same page.
2) Now, I assume, you call the function retrieve() at the end of
the page which in turn, after you hit the link, appends
'view/invoice.php' to the page, so you see the appended content at the
end.
Now, you want to get the link to open the new page, there are two ways:
1) You redirect the page to the page view/invoice.php and there you
call the function retrieve and include target="self" in the anchor tag.
Or
2) You do what you are doing but include target="blank" in the
anchor tag.
In order to get the link to open as fresh content, do as follows:
1) Add javascript to the page. In the Html Head section add the
following lines:
<script type="text/javascript">
function hideMainContentDiv(){
document.getElementById("mainContent").setAttribute("style", "display:none");
}
</script>
2) Add the onclick attribute to the anchor tag as:
<a onclick="hideMainContentDiv()">
3) Now, enclose the content of the page in and give it
id="mainContent" as:
<div id="mainContent"> <!-- All your content --> </div>
4) At the end of the page when you have enclosed your content, add
another div and call your function retrieve as:
<div id="newContent">
<?php retrieve($class,$id); ?>
</div>
What this will do is:
When you click the link, it will call the javascript and hide all your existing page content in the div whose id="mainContent".
When your function retrieve() will be called, it will include 'view/invoice.php' which will show your new content.
Your old content has already been hidden by javascript call.
I hope this resolves your query.
The answer turned out to be sessions.
case 'InvoiceLineItems':
$partnerInfo = $this->partnerInfo->getPartnerInfo($id);
$invoiceLineItems = $this->invoiceLineItems->getInvoiceLineItems($id);
$_SESSION['partnerInfo'] = $partnerInfo;
$_SESSION['invoiceLineItems'] = $invoiceLineItems;
ob_start();
header('Location: /view/invoice.php');
ob_end_flush();
exit();
break;
I added the array data to two session variables in the controller. Then, in the view, I replaced the corresponding variable names -- $partnerInfo and $invoiceLineItems -- with their session equivalents $_SESSION['partnerInfo'] and $_SESSION['invoiceLineItems'].

Categories