Creating a custom button in PHP

Currently, I am in the process of developing a shopping cart feature. One key requirement is to send both the product ID and the desired quantity chosen by the user to another file named cart.php.

Below is an excerpt from my code snippet:

for($i=0;$i<$numOfRows;$i++){
  $prodID=mysql_result($result, $i, "ProductID");
  $prodTitle=mysql_result($result, $i, "Title");
  $prodAuthor=mysql_result($result, $i, "Author1");
  $prodPrice=mysql_result($result, $i, "Price");

  Print"<h4>ID: $prodID \n     </h4>";
  Print"<h4>Title: $prodTitle \n       </h4>";
  Print"<h4>Author: $prodAuthor \n     </h4>";
  Print"<h4>Price: $ $prodPrice \n     </h4>";

  Print" <form method ='POST'>";
  Print"<p><label> Quantity";
  Print"<input name='quantity' type='text' pattern='[1-9]{1,50}'/>";
  Print"</label>";
  Print"<input type='button' value='Add To Cart' onClick='cart.php?pid=$prodID'/>";
  Print"</p></form>";
}

I tried using just

<a href='cart.php?pid=$prodID'>Add To Cart</a>
, which sends the product ID successfully, but I also need to include the quantity parameter in the request. Despite this, when I click on Add To Cart, it fails to redirect me to the cart.php page as intended.

Answer №1

To utilize the POST method, include a hidden input with the PID details. Here is an illustrative example:

echo "<form method ='POST' action ='cart.php'>";
echo "<p><label> Quantity";
echo "<input name='quantity' type='text' pattern='[1-9]{1,50}'/>";
echo "</label>";
echo "<input type='hidden' name = 'pid' value='$prodID'>";
echo "<input type='button' value='Add To Cart'/>";
echo "</p></form>"; 

If you prefer to use the GET method, refer to the @Specter response

Answer №2

Instead of complicating things, why not just submit the form normally using a type="submit" with method="GET":

echo "<form method ='GET' action='cart.php'>";
    echo "<p><label> Quantity: ";
        echo "<input name='quantity' type='text' pattern='[1-9]{1,50}'/>";
    echo "</label>";
    echo "
        <input type='hidden' name='pid' value='$prodID' />
        <input type='submit' value='Add To Cart' />
    ";
echo "</p></form>";

In the file cart.php, simply use $_GET for all variables:

<?php

if(!empty($_GET['quantity']) && !empty($_GET['pid'])) {
    $quantity = $_GET['quantity'];
    $pid = $_GET['pid'];
    // continue with the remaining code
}

A quick reminder:

Avoid using mysql_* functions in your code. These functions are no longer maintained and officially deprecated. Consider using PDO or MySQLi instead of mysql_*. Here's a helpful red box to guide you. Learn about prepared statements and choose between PDO or MySQLi - this article can help you make the right decision. For PDO users, check out this tutorial.

Answer №3

Your onclick event is set to use the GET method, while your form is expecting the POST method and you have not specified the action to be 'cart.php' in your form tag... there could be other issues as well...

Here's a suggestion:

for($i=0;$i<$num Of Rows; $i++)
{
   $prodID=mysql_result($result, $i, "ProductID");
   $prodTitle=mysql_result($result, $i, "Title");
   $prodAuthor=mysql_result($result, $i, "Author1");
   $prodPrice=mysql_result($result, $i, "Price");

   Print"<h4>ID: $prodID \n    </h4>";
   Print"<h4>Title: $prodTitle \n      </h4>";
   Print"<h4>Author: $prodAuthor \n    </h4>";
   Print"<h4>Price: $ $prodPrice \n    </h4>";

   Print"<form action='cart.php' method ='POST'>";
   Print"<p><label> Quantity";
   Print"<input name='pid' type = 'hidden' value='$prodID'>";
   Print"<input name='quantity' type='text' pattern='[1-9]{1,50}'/>";
   Print"</label>";
   Print"<input type='submit' value='Add To Cart'>";
   Print"</p></form>";
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Avoiding scrolling when a button (enveloped in <Link> from react-scroll) is pressed in React

Currently, I am implementing the smooth scroll effect on a component using react-scroll. However, adding a button inside the component to create a favorite list has caused an issue where the smooth scroll effect is triggered upon clicking the button. Is ...

How to style HTML li elements to wrap like sentences within a paragraph

I am looking to format text list elements in a way that they wrap like sentences within a paragraph. Here is the accompanying HTML & CSS code snippet that demonstrates how li element behaves when it exceeds the width of the ul container. ul { ...

What is the best way to show the totals on a calculator screen?

As part of my work, I created a calculator to help potential clients determine their potential savings. Everything seems to be working fine, except for the total fees not appearing for all the boxes. I believe I might be missing the correct process to add ...

The JSON index is beyond the range [0..1)

I have been attempting to retrieve data from a MySql database using Volley in a JSONArray. The PHP script used to fetch rows from the table is shown below: <?php ob_start(); header('Content-Type: application/json'); $con=mysqli_connect("local ...

How can I format time display as shown in Laravel 5.2?

I am currently working with Laravel 5.2 and I would like to display the creation time of articles in a specific format: created_at displaying in 1 day today 2-10 days ...

Creating multiple div elements with changing content dynamically

I am facing an issue with a div named 'red' on my website where user messages overflow the 40px length of the div. To prevent this, I want to duplicate the 'red' div every time a message is sent so that the messages stay within the boun ...

Editing HTML on an ASPX website can be a breeze with

Hello there, I've been tasked with editing a website for a client, but the site is located on a local web server and was designed using aspx. As I review all the files, I am encountering difficulty finding the HTML code associated with runat=server w ...

Warning notification prior to data deletion

I need help with adding a popup message before confirming deletion of data in this code. Here is the current code snippet. while ($test = mysql_fetch_array($result)) { $id = $test['FailID']; echo "<tr align='center'>"; ...

problems with verifying your domain in Google apps

I'm sorry for reaching out here instead of Google's forums, but I haven't had any luck finding answers there. Currently, I have a domain verified on Google Apps by uploading an HTML file, which is being used for email services. I don' ...

Asking for information regarding RESTful API

Could you please assist me in identifying the most suitable technologies for integrating a RESTful API into an HTML and CSS website? The primary objective is to enable the website owner to easily log in and add news entries about their business. Addition ...

Class for managing the connection between MongoDB and PHP

Currently, I am seeking a reliable example of developing a PHP class that can manage connections to multiple MongoDB databases. In my current project, I need to interact with at least five distinct databases. It would be quite resource-intensive if I had t ...

The design I created includes a horizontal scroll feature and certain elements are not properly aligned in the

Oh man, I'm really frustrated right now. I want all my elements to be centered horizontally on smaller devices, but some of them are slightly off to the side. And to top it off, there's a horizontal scroll appearing - it's like something is ...

Disappearing sticky-top navbar in Bootstrap when scrolling

I'm having trouble with the navbar on my website. Currently, it sticks to the top until I scroll out of the hero-image and then disappears. I would prefer the navbar to remain present throughout the entire page. Any suggestions on how to achieve this? ...

Struggling with creating a loop using foreach in combination with MySQL INSERT

I was curious about the possibility of creating a dynamic table for inserting into mysql. I have a small table that users can expand as needed to add more input rows. <script> var count = 0; $(function(){ $('p#add_field').click(function(){ ...

Having difficulty aligning the container div in the center

I'm trying to create a centered grid of full-width buttons, but for some reason, I just can't seem to get the container centered. Any suggestions? Check out the code here - https://jsfiddle.net/a6qo6tzL/ Thank you! <div class="Wrapper"> ...

Tips for displaying an image using the image tag in jQuery

I am looking to dynamically append a share button image after every image tag that meets certain criteria. For the code snippet and demonstration, you can visit this fiddler link here. $(document).ready(function() { $("img").each(function() ...

Is it necessary to specify a data type for the response when making an AJAX POST request?

After carefully reviewing my code, I have ensured that all the variables in my JavaScript match and are properly set up. Additionally, I have confirmed that all the variables in my data array for my AJAX request correspond correctly to my $_POST['var& ...

Resolving Anchor Problems in PHP

I'm struggling with a line of code and need some help: echo "<td>"<a href="userdetails.php?".$row[username].">View Details</a></td>"; When I try to create the link on a page, I want it to be in the format userdetails.php?USER ...

What is the method to incorporate spread into inner shadow within an SVG file?

Seeking assistance with creating an inset-shadow effect with spread for an SVG rectangle in Figma. Check out this example of a rectangle with inner-shadow and spread. I have successfully added blur and positioned the shadow using x and y coordinates, but ...

How can the condition for rewriting the request file name be written as something other than the specified

I am currently dealing with an issue regarding htaccess. I need to create a condition that will prevent a specific file from being served. If the requested file exists, it should be served. Here is what I have so far: RewriteCond %{REQUEST_FILENAME} -f R ...