-4

I'm trying to insert items into a table but it isn't working although it's displaying a successful message :/

Here's my code & table.

<?php 
    ini_set("log_errors", 1);
    ini_set("error_log", "error.log");
    error_log( "Hello, errors!" );

        $itemName = $_POST['itemName'];
        $itemDesc = $_POST['itemDesc'];
        $itemSlutID = $_POST['itemSlutID'];

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

                if (empty($itemName) || empty($itemDesc) || empty($itemSlutID)){
                    echo error('Please fill in all fields');

                }else{
                    $SQLinsert = $odb -> prepare("INSERT INTO `items` VALUES(NULL, :userID, :itemName, :itemDesc, :itemSlutID)");
                    $SQLinsert -> execute(array(':userID' => $_SESSION['ID'], ':itemName' => $itemName, ':itemDesc' => $itemDesc, ':itemSlutID' => $itemSlutID));
                    echo success('Item has been added, please wait up to 1 hour for us to approve the item.');
                }
            }
?>

CREATE TABLE `items` (
  `ID` int(11) NOT NULL,
  `userID` int(11) NOT NULL,
  `itemName` text NOT NULL,
  `itemDesc` text NOT NULL,
  `itemSlutID` text NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
Omal Perera
  • 2,971
  • 3
  • 21
  • 26
SevnDK
  • 31
  • 8

2 Answers2

2

Spot the problem:

$SQLinsert = $odb -> prepare("INSERT INTO `items` VALUES(NULL, :userID, :itemName, :itemDesc, :itemSlutID)");
                                                          ^--- ID field


CREATE TABLE `items` (
  `ID` int(11) NOT NULL,
                ^^^^^

Since you never bothered to check if the query actually succeeded, and blindly (and WRONGLY) output a false "success" message, you ended up here...

Why are you inserting a null value into a field you've explicitly defined as "not null"?

Marc B
  • 356,200
  • 43
  • 426
  • 500
2

1. null

Look at your first column:

ID int(11) NOT NULL,

Yet your first placeholder value is NULL. Better practice would be to change it to NULL AUTO_INCREMENT.

2. Saying "success" whatever happens

After the statement executes, you're not checking to see if it was successful - you're just echoing a statement.

Change:

$SQLinsert -> execute(array(':userID' => $_SESSION['ID'], ':itemName' => $itemName, ':itemDesc' => $itemDesc, ':itemSlutID' => $itemSlutID));
echo success('Item has been added, please wait up to 1 hour for us to approve the item.');

To:

if($SQLinsert -> execute(array(':userID' => $_SESSION['ID'], ':itemName' => $itemName, ':itemDesc' => $itemDesc, ':itemSlutID' => $itemSlutID))){
    echo success('Item has been added, please wait up to 1 hour for us to approve the item.');
} else {
    //There's been a problem!
    echo "ERROR: " . $SQLinsert->errorInfo();
}
Community
  • 1
  • 1
Ben
  • 8,894
  • 7
  • 44
  • 80