php pdo update only changes value in array

I'm very new in pdo, so I only need the changed value or values that post from html as array (Items[]) , this code below updates posted values and puts the unchanged value become to zero. please help and thanks.

<?php

 if(isset($_POST['update'])) {

  for($t=0;$t<8;$t++){ 

       if(isset($_POST['Items'])) {
         $items=$_POST['Items'];
         $update="UPDATE items SET Updater = :LogName, 
         UptoDate = :uptodate, 
         ItemPrice = :Items  
         WHERE id = $t";
          $y=$t-1;
          $stmt=$Link->prepare($update);
          $stmt->bindParam(':Items',$items[$y], PDO::PARAM_STR);
          $stmt->bindParam(':uptodate', $date, PDO::PARAM_STR); 
          $stmt->bindParam(':LogName', $LogName, PDO::PARAM_STR); 
          $stmt->execute();

     } else {
        // Don't do anything because it means there is no $_POST['Items(t)']
    } 
  }
}        
?>

.........

</tr>
  </table> 
   <input type="submit" name="update" value="تحديث"/>
  </form>

Answers


Load the current data from database into an array (format it properly), then use array_diff to get the differences between the database and the form data, so you can build the UPDATE statement as you wish.

You could also specify a default value for fields which wasnt filled, so when they arrive to your server, you know which ones have changes (those with a value different from default one)


Eurekaaaa. i solve it:

 if(isset($_POST['update'])) {
        $Items=$_POST['Items'];
        for($t=0;$t<8;$t++){
            if((!isset($Items[$t])) or ($Items[$t]==="") or ($Items[$t]===0))
                {$t++;}
        elseif(isset ($Items[$t])){
         $y=$t+1;
        $update="UPDATE items SET Updater = :LogName, 
        UptoDate = :uptodate, 
        ItemPrice = :Items  
        WHERE id = $y";

        $stmt=$Link->prepare($update);
        $stmt->bindParam(':Items',$Items[$t], PDO::PARAM_STR);
        $stmt->bindParam(':uptodate', $date, PDO::PARAM_STR); 
        $stmt->bindParam(':LogName', $LogName, PDO::PARAM_STR); 
        $stmt->execute();

    }}}

Update queries will only update rows that need to be changed. You can get the affected rows (http://php.net/manual/en/pdostatement.rowcount.php) which will tell you how many rows were updated. Unless you specifically need the changed values (in which case you'll need to select them first), I believe the code will handle what you need automatically.


Need Your Help

Get raw URL from Microsoft.AspNet.Http.HttpRequest

request uri asp.net-core

The HttpRequest class in Asp.Net 5 (vNext) contains (amongst other things) parsed details about the URL for the request, such as Scheme, Host, Path etc.