-1

I am new to php. I coded so far the products page who fetch from database and now I want to start coding the "add to cart" button that sends items to a cart database table.

I really would appreciate if anyone can tell me where should I start. I tried so many ways and it failed to send data to cart. This is my code:

<div id="product-grid">

  <div class="product-item">
    <form method="post" action="add.php">
    <input type="hidden" class="product-image" name="image"><img src="<?php echo $products[$i]["image"]; ?>">
    <div class="product-tile-footer">
    <input type="hidden" class="product-title" name="name"><b><?php echo $products[$i]["name"]; ?></b> <br>
    <input type="hidden" class="product-price" name="price"><?php echo "$".$products[$i]["price"]; ?>
    <div class="cart-action"><input type="text" class="product-quantity" name="quantity" value="1" size="2" />
    <input type="submit" value="Add to Cart" name="add" class="btnAddAction"/></div>
    </div>

    </form>
  </div>
</div>

<?php
}
?>

add.php

<?php
session_start();
$link = mysqli_connect("localhost", "root", "", "MyGym") or die("DB Connection error");

if(isset($_POST['add']))
{    
     $email=$_SESSION['email'];
     $image = $_POST['image'];
     $name = $_POST['name'];
     $code=$_POST['code'];
     $price = $_POST['price'];
     $qty=$_POST['quantity'];
     $sql = "INSERT INTO cart (email,image,name,code,price,quantity)
     VALUES ('$email','$image','$name','$code','$price','$qty')";
     if (mysqli_query($link, $sql)) {
        echo "Added To cart !";
        header("location:Store.php");
     } else {
        echo "Error: " . $sql . ":-" . mysqli_error($link);
     }
     mysqli_close($link);
}
?>
Twisty
  • 30,304
  • 2
  • 26
  • 45
  • Looks like you've got a form. Where is your code for grabbing the form values, user info, and submitting to the database? – JNevill Jun 22 '21 at 16:27
  • i just edited the question ,and posted the add.php i would apreciate any help – waleed nader Jun 22 '21 at 16:47
  • `if(isset($_POST['Add to Cart'])` is wrong - you're testing the value, but what you should be testing is the _name_ - the value, if it was sent, will be _within_ `$_POST['add']`. So `if(isset($_POST['add'])` is what you would need. – ADyson Jun 22 '21 at 16:48
  • 3
    P.S. **Warning:** Your code is vulnerable to SQL Injection attacks. You should use parameterised queries and prepared statements to help prevent attackers from compromising your database by using malicious input values. http://bobby-tables.com gives an explanation of the risks, as well as some examples of how to write your queries safely using PHP / mysqli. **Never** insert unsanitised data directly into your SQL. The way your code is written now, someone could easily steal, incorrectly change, or even delete your data. – ADyson Jun 22 '21 at 16:48
  • 2
    https://phpdelusions.net/mysqli also contains good examples of writing safe SQL using mysqli. See also the [mysqli documentation](https://www.php.net/manual/en/mysqli.quickstart.prepared-statements.php) and this: [How can I prevent SQL injection in PHP?](https://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php) . Parameterising your queries will also greatly reduce the risk of accidental syntax errors as a result of un-escaped or incorrectly quoted input values. At the moment someone could break your query just by putting a `'` (apostrophe) in one of the input fields! – ADyson Jun 22 '21 at 16:48
  • 1
    Also, mever configure your web app to login to the database as root. Root can do whatever it likes, so on top of the SQL injection vulnerabilities this just leaves your database an open book for hackers. Instead create a separate user account specifically for this application which has only the permissions it actually _needs_ in order to work properly. Don't even use the root account as a shortcut during development or testing, because you need to test your account permissions as well - otherwise when you go live you might have unexpected errors relating to the user account setup. – ADyson Jun 22 '21 at 16:49
  • divs are not inputs, they don't have name attributes, add hidden inputs – Lawrence Cherone Jun 22 '21 at 16:51
  • So i changed the isset and the divs to hidden inputs but it send empty strings to database – waleed nader Jun 22 '21 at 17:23
  • 1
    In your HTML, I see no `value` attribute for your `input` elements. This is why when you call them in PHP there is no Value, just an empty String. – Twisty Jun 22 '21 at 17:51
  • If you are only starting to learn PHP then you should learn PDO instead of mysqli. PDO is much easier and more suitable for beginners. Start here https://phpdelusions.net/pdo & https://websitebeaver.com/php-pdo-prepared-statements-to-prevent-sql-injection – Dharman Jun 30 '21 at 13:13
  • What **exactly** is not working with the given code? What have you tried to make it work? Would it help to use the `value` attribute of these hidden fields? – Nico Haase Jun 30 '21 at 13:14

1 Answers1

0

On a high level, you should simply need to reference the Product ID when a User wants to add a Product to their Cart. The Product ID will be a unique identifier that your PHP Script can use to gather all the details about the Product as needed.

Consider the following HTML.

<div id="product-grid">
  <div class="product-item">
    <img src="<?php echo $products[$i]['image']; ?>">
    <div class="product-tile-footer">
      <b><?php echo $products[$i]["name"]; ?></b>
      <?php echo "$".$products[$i]["price"]; ?>
      <form method="POST" action="add.php">
        <div class="cart-action">
          <input type="text" class="product-quantity" name="quantity" value="1" size="2" />
          <button type="submit" value="<?php echo $products[$i]['id']; ?>" name="add" class="btnAddAction" />Add To Cart</button>
        </div>
      </form>
    </div>
  </div>
</div>

With this form, you have the Quantity and the Product ID being passed to your PHP. That should be all that you really need in your Cart or Session data.

It is best to separate HTML and PHP, such that you don't have inline PHP in your HTML. If you are going to do this, it is a good practice to switch the Quotes. So if you are wrapping your PHP with Double Quotes ", then use Single Quotes ' in your PHP.

Consider the following PHP.

<?php

session_start();
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$link = mysqli_connect($DB_Server, $DB_User, $DB_Pass, $DB_Name);

if (isset($_POST['add'])) {
    $email = $_SESSION['email'];
    $qty = intval($_POST['quantity']);
    $pid = $_POST['add'];
    $stmt = mysqli_prepare($link, "INSERT INTO cart (email,quantity,id) VALUES (?, ?, ?)");
    mysqli_stmt_bind_param($stmt, "sis", $email, $qty, $pid);
    mysqli_stmt_execute($stmt);
    echo "Added To cart!";
    header("location:Store.php");
}

It is never a good idea to allow the User to define what is used in POST. For example, a Bad Actor could place an item in the cart with a 0 for the Price. They would just generate their own POST Data via the browsers console and set their own price.

This is why you want to limit what is passed between the Form and the PHP Script. This way the User cannot manipulate it. Using the Prepared Statement allows you to better control the Input of data to the Database. This helps defeat SQL Injection.

See more:

When the User goes to their Cart, your PHP script can perform a more complex SQL Query to collect all the Product Details to show on the page. This will be a INNER JOIN type of query where the Cart table can cross reference the Product details based on the common Product ID.

Example: https://www.w3schools.com/sql/sql_join.asp

SELECT cart.quantity, product.image, product.name, product.price
FROM cart
INNER JOIN products AS product ON cart.id=product.id
WHERE cart.email = '$_SESSION["email"]';

Fiddle: http://sqlfiddle.com/#!9/9da02f/3/0

Dharman
  • 30,962
  • 25
  • 85
  • 135
Twisty
  • 30,304
  • 2
  • 26
  • 45