HTML — PHP Форма отправить $ _POST в корзину

Во-первых, я показываю список продуктов. Я хочу, чтобы эти продукты были введены в форму и генерировать уникальные кнопки (я думаю, что я делаю эту часть правильно). Однако всякий раз, когда я отправляю, например, продукт 2, он сразу переходит к другому и принимает значение 6.

 function displayData($result){
print "<table border = 1 >";
print '<form id="form1" name="form1" method="post" action="cart.php">';
while ($row = $result->fetch_assoc()){
$image = $row["Image"];
print "  <tr>";
print "    <td valign='top'><ul><li>ID: " . $row["id"] . "</li><br />";
?>
<input type="hidden" name="<?php echo $row["id"]; ?>" id="<?php echo $row["id"]; ?>" value="<?php echo $row["id"]; ?>"/>
<input type="submit" name="button<?php echo $row["id"]; ?>" id="button<?php echo $row["id"]; ?>" value="Add item <?php echo $row["id"]; ?>"/> <br><?php
print "    <li>Name: " . $row["Name"] . "</li><br />";
print "    <li>Tag: " . $row["Tag"] . "</li></td></ul>";
print "    <td valign='top'>" . $row["Description"] . "</td>";
print "    <td> <img width=150px height=150px src='../../assets/images/$image'></td>";
print "  </tr>";
}
print " </form>";
print "</table>";
}//end of display function

Кажется, что это генерирует кнопки правильно со значениями, такими как «button1» и «button2», теперь в моей корзине я пытаюсь назначить отправку правильному идентификатору продукта, в данный момент он просто вводит значение 6.

if (isset($_POST['button1'])) {
$pid = 1;
} else if (isset($_POST['button2'])) {
$pid = 2;
} else if (isset($_POST['button3'])) {
$pid = 3;
} else if (isset($_POST['button4'])) {
$pid = 4;
} else if (isset($_POST['button5'])) {
$pid = 5;
} else  {
$pid = 6;
$wasFound = false;
$i = 0;
//If the cart session variable is not set or cart array is empty
if (!isset($_SESSION["cart_array"])||count($_SESSION["cart_array"])<1){
//Run if the cart is empty or not set
$_SESSION["cart_array"] = array(1 =>array("item_id" => $pid, "quantity" => 1));
} else {
//Run if the cart has at least one item in it
foreach($_SESSION["cart_array"] as $each_item){
$i++;
while(list($key, $value) = each($each_item)) {
if ($key == "item_id" && $value==$pid) {
//That item is in the cart already so just adjust the quantity using array splice()
array_splice($_SESSION["cart_array"], $i-1, 1, array(array("item_id" => $pid, "quantity" => $each_item['quantity']+1)));
$wasFound = true;
} //Close if condition
} //Close while loop
} //Close foreach loop
if ($wasFound == false) {
array_push($_SESSION["cart_array"], array("item_id" => $pid, "quantity" =>1));
}//Close if statement
}//Close if statement
}

Это вывод HTML-формы — по запросу.

<table border = 1 ><form id="form1" name="form1" method="post" action="cart.php">  <tr>    <td valign='top'><ul><li>ID: 1</li><br />          <input type="hidden" name="1" id="1" value="1"/>
<input type="submit" name="button1" id="button1" value="Add item 1"/> <br>    <li>Name: Hamburger</li><br />    <li>Tag: Burger</li></td></ul>    <td valign='top'>A minced beef patty in between some bread</td>    <td> <img width=150px height=150px src='../../assets/images/burger.jpg'></td>  </tr>  <tr>    <td valign='top'><ul><li>ID: 2</li><br />          <input type="hidden" name="2" id="2" value="2"/>
<input type="submit" name="button2" id="button2" value="Add item 2"/> <br>    <li>Name: Cheeseburger</li><br />    <li>Tag: Burger</li></td></ul>    <td valign='top'>A minced beef patty with cheese in between some bread</td>    <td> <img width=150px height=150px src='../../assets/images/cheeseburger.jpg'></td>  </tr>  <tr>    <td valign='top'><ul><li>ID: 3</li><br />          <input type="hidden" name="3" id="3" value="3"/>
<input type="submit" name="button3" id="button3" value="Add item 3"/> <br>    <li>Name: Chicken Burger</li><br />    <li>Tag: Burger</li></td></ul>    <td valign='top'>A butter flied chicken breast in between some bread</td>    <td> <img width=150px height=150px src='../../assets/images/chickenburger.jpg'></td>  </tr>  <tr>    <td valign='top'><ul><li>ID: 4</li><br />          <input type="hidden" name="4" id="4" value="4"/>
<input type="submit" name="button4" id="button4" value="Add item 4"/> <br>    <li>Name: Spaghetti Bolognese</li><br />    <li>Tag: Pasta</li></td></ul>    <td valign='top'>Traditional Italian pasta dish</td>    <td> <img width=150px height=150px src='../../assets/images/bolognese.jpg'></td>  </tr>  <tr>    <td valign='top'><ul><li>ID: 5</li><br />          <input type="hidden" name="5" id="5" value="5"/>
<input type="submit" name="button5" id="button5" value="Add item 5"/> <br>    <li>Name: Sirloin</li><br />    <li>Tag: steak</li></td></ul>    <td valign='top'>God tier beef</td>    <td> <img width=150px height=150px src='../../assets/images/steak.jpg'></td>  </tr> </form></table>

заранее спасибо

0

Решение

Вместо того, чтобы пытаться выбирать элементы с громоздким оператором if, гораздо лучше работал цикл for. Вот код, который заставил его работать.

$result = $mysqli_conn->query("SELECT DISTINCT id FROM Food");
//print " Query returned ". $result->num_rows . " rows ";;
$len = $result->num_rows;
for($k=1; $k<=$len; $k++)
{
if (isset($_POST['button'.$k]))
{
$pid = $k;
}
}
0

Другие решения

Других решений пока нет …

По вопросам рекламы ammmcru@yandex.ru
Adblock
detector