Skip to content
Advertisement

Saving items by multiple users in database

What am doing wrong ? this might be the simple solution to all experts here, but i have tried all the ways and i dont know where is my mistake ?

The idea is to add and items through my page to my database and then i can check them as todo list or to buy list. As well is in future this will be toBuy/toDo list web application so whole family members add items and in the end of the day one refresh the page and get the whole items in the database fetched!

my codes are below:

TodoTobuy.php

<?php
include("includes/header.php");
include("./forms/fadd-items.php")
?>


<?php

try {

    //Tiedot kantaan
    
    /* var_dump($_POST); */

    $data1['items'] = $_POST['givenItems'];
    $data1['amount'] = $_POST['givenAmount'];


    $STH = $DBH->prepare("INSERT INTO todoORtobuy (items, amount, id) VALUES (:items, :amount, :id);");
    $STH->execute($data1);

    $data4['id'] = $data1['id'];
    $sql4 = "SELECT id FROM todoORtobuy where id =:id ORDER BY start DESC LIMIT 50";

    $kysely4 = $DBH->prepare($sql4);
    $kysely4->execute($data4);
    $tulos2 = $kysely4->fetch();

    $_SESSION["startDate"] = $tulos2[0];
    
} catch (PDOException $e) {
    echo "Yhteysvirhe: " . $e->getMessage();
    file_put_contents('log/DBErrors.txt', 'Connection: ' . $e->getMessage() . "n", FILE_APPEND);
}

?>

My form

<fieldset>
<form method="post">
  <p>
  Items toDo  toBuy:
  <br />  <input type="text" name="givenItems" placeholder="Write what toDOtoBuy..." maxlength="100"/>
  </p><p>
  Amount needed:
  <br />  <input type="text" name="givenAmount" placeholder="Write amount of what to buy..." maxlength="100"/>
  </p>

  <br />  <div>
            <input type="submit" name="submitUser" value="Add" id="send" class="sendbutton"/>  
          </div>
  </p>
</form>
</fieldset>

error i get is: SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens

I mean i kindda understand the error, but cant find the mistake! Thank you for helping in advance

Advertisement

Answer

$data1['items'] = $_POST['givenItems'];
$data1['amount'] = $_POST['givenAmount'];


$STH = $DBH->prepare("INSERT INTO todoORtobuy (items, amount) VALUES (:items, :amount);");
$STH->execute($data1);

In your code you are using 3 prepared values for your query but you only pass 2.

Also when inserting you don’t need to insert the id, it should be set as auto-increment in your table and basically takes care of itself for each record you insert.

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