Skip to content
Advertisement

Failing to update rows in the database, only able to update one row with corresponding ID to UserId

I am trying to update rows in a table of items. The database has ID for item id and UserId for the id of the user who created the item. The problem is the the update is only updating the first row which has item ID 1 and UserId 1 thats all. Here is the update query.

<?php
    require_once 'conn.php';

    if(ISSET($_POST['update'])){
        $userid     = $_SESSION['gtsuid'];
        $ItemName   = $_POST['ItemName'];
        $ItemType   = $_POST['ItemType'];
        $Quantity   = $_POST['Quantity'];
        $Price      = $_POST['Price'];
        $Amount     = $_POST['Amount'];
        $BDate      = $_POST['BDate'];

        $query = "UPDATE `items` SET `ItemName` = :ItemName, `ItemType` = :ItemType, `Quantity` = :Quantity, `Price` = :Price, `Amount` = :Amount, `BDate` = :BDate WHERE `ID` = :userid";

        $stmt = $conn->prepare($query);
        $stmt->bindParam(':ItemName', $ItemName);
        $stmt->bindParam(':ItemType', $ItemType);
        $stmt->bindParam(':Quantity', $Quantity);
        $stmt->bindParam(':Price', $Price);
        $stmt->bindParam(':Amount', $Amount);
        $stmt->bindParam(':BDate', $BDate);
        $stmt->bindParam(':userid', $userid);

        $stmt->execute();
        $conn = null;

        header('location: index.php');

    }
?>

And the database:

database

I really don’t know where I am going wrong as I am still new to this.

Advertisement

Answer

Got the issue sorted out. Here is the solution in case of future reference. SOLUTION: 1. Declare ID like this: $ID = $_POST[‘ID’]; as shown below;

if(ISSET($_POST['update'])){
    $userid     = $_SESSION['gtsuid'];
    $ID         = $_POST['ID'];
    $ItemName   = $_POST['ItemName'];
    $ItemType   = $_POST['ItemType'];
    $Quantity   = $_POST['Quantity'];
    $Price      = $_POST['Price'];
    $Amount     = $_POST['Amount'];
    $BDate      = $_POST['BDate'];

Then also bind the ID.

$stmt = $conn->prepare($query);
    $stmt->bindParam(':userid', $userid);
    $stmt->bindParam(':ID', $ID);
    $stmt->bindParam(':ItemName', $ItemName);
    $stmt->bindParam(':ItemType', $ItemType);
    $stmt->bindParam(':Quantity', $Quantity);
    $stmt->bindParam(':Price', $Price);
    $stmt->bindParam(':Amount', $Amount);
    $stmt->bindParam(':BDate', $BDate);
  1. Echo the ID on submit button like this:

In my case I was missing the statements below:

  $ID = $_POST['ID'];
  $stmt->bindParam(':ID', $ID);
  <?php echo $row['ID']; ?>

Hitherto, thank you all for your contributions.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement