-1

I am creating dynamic textfields buy using following Jquery option

Jquery Code

<script>
    $(function () {
        $('input.more').on('click', function () {
            var $table = $('#input_fields');
            var $tr = $table.find('tr').eq(0).clone();
            $tr.appendTo($table).find('input').val('');
        });
    });
</script>

and Inserting records to the table using following PHP

$post_count = count($_POST['product']);
$post1 = array();
$post2 = array();
$post1 = $_POST['product'];
$post2 = $_POST['quantity'];
for ($i = 0; $i <= $post_count; $i++) {
    $sql[] = "INSERT INTO product (product,quanity) VALUES ('".$post1[$i]."','".$post2[$i]."')";
}
foreach ($sql as $query) {
    mysqli_query($conn, $query);
}
?>

1)the stock Id is retrieving from a table.

I want to know when I enter product and quantity ,how can I keep the same Stock Id in dynamically created text fields and insert data in to the database

Cœur
  • 32,421
  • 21
  • 173
  • 232

1 Answers1

0

First of all stop using the mysql_ and mysqli_ libraries.
They are dangerously outdated and should never be used because of SQL injection issues.

If you want to execute a loop you need to put all your logic in the same loop.
Something like this:

//connect to DB 
$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
$post_count = count($_POST['product']);
$post1 = array();
$post2 = array();
$post1 = $_POST['product'];
$post2 = $_POST['quantity'];
//prepare your statement
$stmt = $dbh->prepare("INSERT INTO product (product,quantity) VALUES (?, ?)");
$stmt->bindParam(1, $product);
$stmt->bindParam(2, $quantity);
for ($i = 0; $i <= $post_count; $i++) {
  $product = $post1[i];
  $quantity = $post2[i];
  //execute the prepared statement with your parameters.
  $stmt->execute();
}

Note that this code uses PDO with parameters which is inherently save from SQL injection issues, runs much faster and is easier to work with.

If you want to do the inserts faster you can put them in a single insert statement using code like this: How to insert an array into a single MySQL Prepared statement w/ PHP and PDO

Community
  • 1
  • 1
Johan
  • 71,222
  • 23
  • 174
  • 298