Tuesday, 23 October 2018

Script posts the first number in value

I am trying to post data to my database. When I post the data I can see that the first number of the value is posted to the database:

Example: I want to post the value 15. The script posts 1.

I want to post the value 550. The script posts 5.

I want to post the value 30. The script posts 3.

Does someone know the reason for that?

Here is my script:

<input type="text" id="quantity" name="quantity" value="15" />
<input type="text" id="name" name="name" value="550" />
<input type="text" id="price" name="price" value="30" />

<?php
  for($count=0; $count<$_POST["total_item"]; $count++)
  {
    $db3 = new PDO('mysql:host=localhost;dbname=db', 'root', 'pass');

    $query3= "INSERT INTO scu_test(id, quantity, name, price) VALUES (:id, :quantity, :name, :price)";
    $stmt3 = $db3->prepare($query3);
    $exec3 = $stmt3->execute(array(
      ':id'          =>  $_SESSION['id'],
      ':quantity'    =>  $_POST["quantity"][$count],
      ':name'        =>  $_POST["name"][$count],
      ':price'       =>  $_POST["price"][$count]
    ));
    if($exec3)
      {
        header('Location: ../succ.php');
      }
  }
?>

Update 1:

With the answer of Justinas I build the following script:

Dynamic rows:

<input type="text" id="quantity1" name="quantity" value="15" />
<input type="text" id="name1" name="name" value="550" />
<input type="text" id="price1" name="price" value="30" />

<input type="text" id="quantity2" name="quantity" value="15" />
<input type="text" id="name2" name="name" value="550" />
<input type="text" id="price2" name="price" value="30" />

Post:

<?php
  foreach($_POST as $i => $item)
  {
    $db3 = new PDO('mysql:host=localhost;dbname=db', 'root', 'pass');

    $query3= "INSERT INTO scu_test(id, quantity, name, price) VALUES (:id, :quantity, :name, :price)";
    $stmt3 = $db3->prepare($query3);
    $exec3 = $stmt3->execute(array(
      ':id'          =>  $_SESSION['id'] . '_' . $i,
      ':quantity'    =>  $_POST["quantity"],
      ':name'        =>  $_POST["name"],
      ':price'       =>  $_POST["price"]
    ));
    if($exec3)
      {
        header('Location: ../succ.php');
      }
  }
?>

When I post the data to the database I get 18 rows in the database. The data that is posted looks like random data with has no relation with the values in quantity, name or price.

Does someone know what is wrong with the script?



from Script posts the first number in value

No comments:

Post a Comment