I have this code in my HTML form:
<form action="cart.php" method="post">
<input type="hidden" value="1" name="sample_" id="sample_">
Sample Bottle <br /><input type="submit" value="Add to Cart" name="sample"><br />
</form>
<h1>Cart Total: $<?php echo $cart; ?></h1>
And then in the referenced cart.php file I have:
$cart = 0;
$samp开发者_如何学Goles = ($_POST['sample_']) * 50;
$cart = $cart + $samples;
echo $cart;'
Unfortunately, this code isn't doing what I want it to and I need some help. Ideally, I simply want the code to add "50" to the Cart, which starts at 0, when the Add to Cart button is pressed.
Example: http://www.craighooghiem.com/linpap/order
Can someone tell me how I can do this in a much simpler way?
Apparently I can use <?=$_SERVER['PHP_SELF'];?>
somehow to perform this function without leaving the file, but everytime I attempt to do that it takes be back to the website's homepage.
I am using a Wordpress template file for the PHP if that makes a difference.
EDIT: I have quickly learned that I am not all that familiar with PHP at all, I barely know the ropes at this point.
To remain on the same page, leave the action
attribute of the form empty eg:
<form method="post" action="">
Now, on submit, it won't go to the site's homepage.
Finally, modify your code like this:
$samples = intval($_POST['sample_']) * 50;
$cart = intval($cart) + $samples;
echo $cart;
<?php
$cart = 0;
// good practice to see if the submit button has been pressed.
if (isset($_POST['submit'])) {
// no need to explicitly cast to an int, PHP is loosely typed.
$samples = ($_POST['sample_']) * 50;
$cart = $cart + $samples;
}
?>
<form action="echo.php" method="post">
<input type="hidden" value="1" name="sample_" id="sample_">
Sample Bottle <br />
<input type="submit" value="Add to Cart" name="submit"><br />
</form>
<h1>Cart Total: $<?php echo $cart; ?></h1>
That code outputs "50" for me.
I had changed the action
attribute to coincide to my PHP file. Also, I changed the name
attribute of my submit button to submit for clarity reasons.
Could it be that you didn't close your input tag for the hidden field? So add
</input>
After it. If that doesn't fix it, make sure you're getting the post variable by echoing it. If that looks right and it's still not working try forcing php to convert to an int with intval (which it should do anyway). Good luck.
精彩评论