-1

The context is: e-commerce, the problem stands in adding items to the cart.

I created a while loop to iterate through each item my query returns and each item has a button that redirects to a "info on the item" page. My problem is that since there's a loop, the values to submit (e.g. the ID of the item) is overloaded and every button submits the values of the last item. I can pass all the IDs of all the plants but i have no idea how to, in the "item detail" page, to show the correct item among the array.

lista-piante.php: (summarized)

<?php session_start();

// connect to the database
$connessione = new mysqli('localhost', 'root', 'root', 'mio');

    //query
    $user_check_query = "SELECT Pianta.NOME as nome, PIANTA.ID as pid, Item.PREZZO as prezzo, Item.ID as id 
    FROM Item, Pianta WHERE Pianta.ID = Item.PIANTA";
    $result = mysqli_query($connessione, $user_check_query);

    if($result->num_rows > 0) {
        echo"<h3>Lista delle nostre piante</h3>";

        echo"<ul class=\"plant-flex\">";

        // loop through records
        while($row = $result->fetch_array(MYSQLI_ASSOC)){

            echo"<form method='get' action='../html/details-pianta.php'>";

            echo"<li>";
            echo"<div class='plant-preview'>";
            echo"<div class='plant-preview-description'>";

            //dichiarazione variabili (per leggibilità)
            $nome= $row['nome'];
            $pid = $row['pid'];

            // PRINT NAME
            echo"<div class='plant-preview-description-name'>";
            echo "<p class='bold'>" . $nome . "</p>";
            echo "<input type='hidden' name='name' value='$nome'  />";
            echo"</div>";


            echo "<input type='hidden' name='pid[]' value='$pid'  />";

            echo"<div>";
            echo"<button type=\"submit\" class=\"btn\" name=\"details_plant\">Dettagli" . $item . "</button>";
            echo"</div>";

            echo"</li>";
            echo"<form/>";

        }
        $result->free();

}
echo "<ul/>";
$connessione->close();

details-pianta.php: (summarized, it will contain the style of the page)

<?php session_start();?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="it" lang="it">


<head> <!-- meta tag and other stuff --> </head>

<body>
            <div>
                <?PHP include('../php/dettagli-pianta.php'); ?>
            </div>
</div>

</body>
</html>

dettagli-pianta.php: (summarized, it should contain the info of each item)

<?php
session_start();

// connect to the database
$connessione = new mysqli('localhost', 'root', 'root', 'mio');

$pid = mysqli_real_escape_string($connessione, $_GET['pid']);


//but pID is either the last item's id, or an array with all items' ids, so i can't chose the only one i want
//the URL shows always more pIDs (from the lista-piante.php get form)

$user_check_query = "SELECT * FROM Pianta, item WHERE Pianta.ID = '$pid' ";
$result = mysqli_query($connessione, $user_check_query);

if($result->num_rows > 0) {


    echo"<h3>Dettagli della pianta</h3>";
    echo"<ul>";

    //loop thought query records
    while($row = $result->fetch_array(MYSQLI_ASSOC)){

        echo"<form method='post' action='../php/add-carrello.php'>";


        echo"<li>";
        echo"<div>";

        //dichiarazione variabili (per leggibilità)
        $nome =$row['NOME'];
        //$genere= $row['GENERE'];
        //$specie= $row['SPECIE'];
        //etc etc


        // PRINT NAME
        echo"<div>";
        echo "<p class='bold'>" . $nome . "</p>";
        echo"</div>";


        //echo"<div>";
        //echo "<p class='bold'>" . $specie. "</p>";
        //echo"</div>";


        //echo "<input type='hidden' name='pid' value='$pid'  />";

        echo"<div>";
        echo"<button type=\"submit\" class=\"btn\" name=\"add-carrello\"> Aggiungi al carrello</button>";
        echo"</div>";

        echo"</li>";

    }
    $result->free();

}
echo "<ul/>";

$connessione->close();
paolodidio
  • 15
  • 7
  • Please @paolodidio look [here](https://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php/60496#60496) for learn how to prevent sql inject (prepare statment), occhio ai hacker ;) – Simone Rossaini May 12 '20 at 07:48
  • 1
    You do not want to submit any actual data here at this point, you want to link to the detail page for the specific product. So these buttons should not be buttons to begin with, they should be _links_. (You should not use HTML elements contrary to their inherent meaning, just because you want to achieve a specific element layout / look, if that was the basis of that choice here. _Format_ your links to _look_ like buttons then.) – CBroe May 12 '20 at 07:52

1 Answers1

0

There is an error with form closing, but... I have a feeling you are complicating it for yourself by using all those forms/buttons.

I would clean up the code and get rid of the form/button scheme altogether, and use simple a href links with ?id=$pid

Something like this (shortened, if needed post a comment and I can expand):

while($row = $result->fetch_array(MYSQLI_ASSOC)){

            echo "<li>";
            echo "<div class='plant-preview'>";
            echo "<div class='plant-preview-description'>";

            //dichiarazione variabili (per leggibilità)
            $nome = $row['nome'];
            $pid = $row['pid'];

            // PRINT NAME
            echo "<div class='plant-preview-description-name'>";
            echo "<p class='bold'>" . $nome . "</p>";
            echo "</div>";

            echo "<div>";
            echo "<a href ='../html/details-pianta.php?pid=$pid'>Dettagli " . $nome . "</a>";
            echo "</div>";

            echo "</li>";

        }

You can use CSS later to make your a-href link look like a button, add image, or play with it any way you like.

Then in the product details page (dettagli-pianta.php) use your product id pretty much same as you already do:

$pid = $_GET['pid']
...
$user_check_query = "SELECT * FROM Pianta WHERE Pianta.ID = '$pid' ";

Here is one Stack Overflow that talks about using link instead form: How send parameter to a url without using form in php?

Edit (mistakes found, more suggestions, in case you still want to keep forms/buttons):

  • you did not close ?> in your examples, but ok, probably just copy/paste here
  • you have $item variable that isn't defined, and not pulled from SELECT query, so I can only assume that is supposed to be $nome (or you deleted something to make it shorter in question and forgot about it)
  • you also probably wanted a space like this (note space after Dettagli)

echo "<button type='submit' class='btn' name='details_plant'>Dettagli " . $nome . "</button>";

  • not sure why you keep files in folders "../html/" and "../php/" when both are with extensions .php, could be confusing for others later working on your code, or ... maybe it's just me
  • you have <?php session_start();?> then under it you include a file that also has <?php session_start();?> ... no need for one of them. Since "details-pianta.php" is in folder "html" I guess you can remove it from there, as you don't need session just to include another PHP file
  • in form you submit name='pid[]' when you should just use name='pid' (no brackets), like this:

    echo "<input type='hidden' name='pid' value='$pid' />";

  • in "dettagli-pianta.php" you have a select like this: $user_check_query = "SELECT * FROM Pianta, item WHERE Pianta.ID = '$pid' "; where you name two tables but don't join them, and I can only assume it should be $user_check_query = "SELECT * FROM Pianta WHERE Pianta.ID = '$pid' ";

  • be careful of uppercase/lowercase in database and column names, try to standardize
  • in one line you echo with mixed quotes something like echo "<bla name='bla'>" and in next you escape quotes like echo "<bla name=\"bla\">" ... make it easy on yourself and - standardize. Unless absolutely necessary, first way (mixing single and double quotes) is preferable, and only when you have something really complicated to echo like mix of HTML+JavaScript, then resort to escaping quotes

And finally, but actually a direct answer to your issue - you closed your form in the wrong way (yeah, had to look real hard to see it):

echo"<form/>";

You need to have (space is optional, reads better):

 echo "</form>";

Non the less, as others too have already commented, using forms just to get buttons is an overkill. Try using simple links (<a href> elements) and style them with CSS to your liking, making them look like buttons...

And last, but... I believe it to be important... Try not to mix Italian and English in code (including database structure). It is obvious you are just learning but havin database called "mio" with table "pianti" and column "prezzo" ... then use something like "item". Also, names of files like "details-pianta", then you have another file "detaggli_pianta", and in button name you use "details_plant", it is huge mashup of two languages. you seem to be fluent English speaker judging from your question, so - why not use English everywhere in code? Name your database "my_first_web_store", name your table "plants", name your column "price", name your PHP files "plant_details" (or details_plant, whatever), use comments in English in your code (nobody but you and other developers see that). You will be thankful later when your plant-selling company expands worldwide, and when you will have multi-language webshop, and maybe 3 more developers working from India and US, all working on same project... :)

Have fun learning!

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
LuxZg
  • 226
  • 2
  • 6
  • 1
    Thank you very much! The answer was straight to the point and I really needed all the other tips! I thought forms were the only way to pass data through pages, but the link is a way more elegant solution to it. My follow-up question is: when do I need forms then? When the amount of data cannot be easily passed in the URL? And another: is it better to pass values between pages or re-use queries? – paolodidio May 12 '20 at 19:24
  • Well, those are good questions. Usually I'm passing values as links with IDs, maybe a marker (eg print or.pdf view), short stuff, single-word values. Obviously I'd never post something like text paragraph or file as URL :) as for query vs passing link... I believe same to be true, couple words can go through URL if it makes sense but usually, just pass ID, and call that from DB again. It's not all black/ white, no right or wrong, you can see big sites passing dozen long strings in URLs, so this is more like my subjective vjew. It's really a question for a poll or a community discussion :) – LuxZg May 12 '20 at 21:32