1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
|
<?php
$link = mysqli_connect("localhost","root","","addrow") or die("Error " . mysqli_error($link));
// store in the DB
if(!empty($_POST['ok'])) {
// first delete the records marked for deletion. Why? Because we don't want to process them in the code below
if( !empty($_POST['delete_ids']) and is_array($_POST['delete_ids'])) {
// you can optimize below into a single query, but let's keep it simple and clear for now:
foreach($_POST['delete_ids'] as $id) {
$sql = "DELETE FROM products WHERE id=$id";
$link->query($sql);
}
}
// now, to edit the existing data, we have to select all the records in a variable.
$sql="SELECT * FROM products ORDER BY id";
$result = $link->query($sql);
// now edit them
while($product = mysqli_fetch_array($result)) {
// remember how we constructed the field names above? This was with the idea to access the values easy now
$sql = "UPDATE products SET qty='".$_POST['qty'.$product['id']]."', name='".$_POST['name'.$product['id']]."'
WHERE id='$product[id]'";
$link->query($sql);
}
// (feel free to optimize this so query is executed only when a product is actually changed)
// adding new products
if(!empty($_POST['qty'])) {
foreach($_POST['qty'] as $cnt => $qty) {
$sql = "INSERT INTO products (qty, name) VALUES ('$qty', '".$_POST['name'][$cnt]."');";
$link->query($sql);
}
}
}
// select existing products here
$sql="SELECT * FROM products ORDER BY id";
$result = $link->query($sql);
while($product = mysqli_fetch_array($result)): ?>
<p id="oldRow<?=$product['id']?>">
Item quantity: <input type="text" name="qty<?=$product['id']?>" size="4" value="<?=$product['qty']?>" />
Item name: <input type="text" name="name<?=$product['id']?>" value="<?=$product['name']?>" />
<input type="checkbox" name="delete_ids[]" value="<?=$product['id']?>"> Mark to delete<
<?php endwhile;?> |
Partager