-1

When i write code in create.php, it gives me error Uncaught PDOException: SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'title' cannot be null.

$title = $_POST['title'];
$description = $_POST['description'];
$price = $_POST['price'];

$statement = $pdo->prepare("INSERT INTO products (title, image, description, price, create_date)
                VALUES (:title, :image, :description, :price, :date)");
$statement->bindValue(':title', $title);
$statement->bindValue(':image', '');
$statement->bindValue(':description', $description);
$statement->bindValue(':price', $price);
$statement->bindValue(':date', date('Y-m-d H:i:s'));

$statement->execute();

I don't understand it

Luuk
  • 12,245
  • 5
  • 22
  • 33
Dave
  • 37
  • 6
  • 2
    It means your title column is `null`. Your title column bind value with `$title` this variable is `null`. The variable `$title` is from `$_POST['title']` but if this post body is not exists then it will be `null`. And if you display all error levels while development calling to `$_POST['title']` while the post body `title` is not exists it will be display warning message. To prevent all this, use `$title = ($_POST['title'] ?? '');`. – vee Mar 22 '22 at 18:17
  • and what can i do? what should i write ? – Dave Mar 22 '22 at 18:21
  • 1
    I'm already write everything in the comment. Please fully read again. – vee Mar 22 '22 at 18:27
  • When you have a column, with a [default value](https://stackoverflow.com/questions/3569347/adding-a-new-sql-column-with-a-default-value), and you set it to `NOT NULL` for that column, and it does not match that value, you will get this error "Column 'title' cannot be null" – Luuk Mar 22 '22 at 18:37
  • and how can i fix it??? – Dave Mar 22 '22 at 18:41
  • First make sure this code only runs on POST requests. Then verify that the required fields have been filled before trying to use their values in the query. – Don't Panic Mar 22 '22 at 18:44

1 Answers1

0

Fix this with PHP's null coalescing operator.

$title = $_POST['title'] ?? '';

Assuming you want a string of length zero to be the default if no title is given in the POST request. If you want the title to be a strong longer than zero characters, you'll have to write some code to check for that.

The null coalescing operator was added in PHP 7.0 (circa 2015), so you should definitely be using a version of PHP that supports it.

Bill Karwin
  • 538,548
  • 86
  • 673
  • 828