INSERT into DB table with PDO prepare and bindParam

后端 未结 3 521
猫巷女王i
猫巷女王i 2020-12-29 14:33

In simple terms can someone explain what I am doing wrong here - I am simply trying to insert into a db with with prepare and bindParam, this is inserting 0 and Null into al

相关标签:
3条回答
  • 2020-12-29 14:41

    Your syntax is incorrect, try this:

    $sql = $db->prepare("INSERT INTO db_fruit (id, type, colour) VALUES (? ,? ,?)");
    $sql->bindParam(1, $newId);
    $sql->bindParam(2, $name);
    $sql->bindParam(3, $colour);
    $sql->execute();
    
    0 讨论(0)
  • 2020-12-29 14:41

    Expanding on A.O's answer, the following are also valid:

    $sql = $db->prepare("INSERT INTO db_fruit (id, type, colour) VALUES (? ,? ,?)");
    $sql->execute(array($newId, $name, $color));
    

    And:

    $sql = $db->prepare("INSERT INTO db_fruit (id, type, colour) VALUES (:id, :name, :color)");
    $sql->execute(array('id' => $newId, 'name' => $name, 'color' => $color));
    

    Might just be personal preference, but I find this syntax to be much cleaner.

    0 讨论(0)
  • 2020-12-29 14:43
    $sql = $db->prepare("INSERT INTO db_fruit (`id`, `type`, `colour`) VALUES (:id, :name, :colour)");
    $sql->bindParam(':id', $newId, PDO::PARAM_INT);
    $sql->bindParam(':type', $type, PDO::PARAM_INT);
    $sql->bindParam(':colour', $colour, PDO::PARAM_STR);
    $sql->execute();
    
    0 讨论(0)
提交回复
热议问题