-3

I want to make that when someone inserts a post into my database that if they don't supply their name it defaults to anonymous. How would I do this? My code here

$query =  "INSERT INTO cinemaPost (name, text, likes, reply_to) VALUES (?, ?, 0, NULL)";

$stmt = $conn->prepare($query);
$stmt->bindValue(1, $post_data['name']);
$stmt->bindValue(2, $post_data['post']);

$stmt->execute();

I have tried doing a default in the create tables for the db but when the user triggers the insert it overides it as a blank field.

CREATE TABLE CinemaPost(
  id INT AUTO_INCREMENT NOT NULL,
  name varchar(255) NOT NULL DEFAULT 'anonymous',
  text varchar(100) NOT NULL,
  post_date timestamp(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6) ON UPDATE CURRENT_TIMESTAMP(6),
  likes INT NOT NULL,
  reply_to INT,
  Primary KEY (id)
); 
3

2 Answers 2

2

The default value will only be used if you don't actually insert to the column i.e. you would need to remove name from the INSERT column list. For example:

if (empty($post_data['name'])) {
    $query =  "INSERT INTO cinemaPost (text, likes, reply_to) VALUES (?, 0, NULL)";
    $stmt = $conn->prepare($query);
    $stmt->bindValue(1, $post_data['post']);
}
else {
    $query =  "INSERT INTO cinemaPost (name, text, likes, reply_to) VALUES (?, ?, 0, NULL)";
    $stmt = $conn->prepare($query);
    $stmt->bindValue(1, $post_data['name']);
    $stmt->bindValue(2, $post_data['post']);
}

It's probably simplest just to check the input value and replace it with "anonymous" if it's empty instead:

$stmt->bindValue(1, empty($post_data['name']) ? 'anonymous' : $post_data['name']);
Sign up to request clarification or add additional context in comments.

3 Comments

Is this question perhaps a duplicate on Stack Overflow, Nick? You don't need rep anymore. Please help the team by closing close-able question instead of answering.
@mickmackusa the only one of those which could be considered to be a duplicate - because it relates to setting a default value in the database - is the first and the answer to that has 2 (of the 3) parts of it which are incorrect (using isset or ??). Additionally that question puts values directly into the query where this one uses a prepared statement. And the answer to that question does not explain why the default value in the table does not get used.
Adjusted the duplicates to show your two techniques demonstrated by the highest voted answer on respective pages. empty() might not be a good call for silly-fringe cases. 3v4l.org/rKSTW
0

Using DEFAULT on the SQL side is absolutely correct. However, you need to ensure that value is actually used.

The default value is only used if you pass NULL as the parameter from PHP. An empty string ("") is not NULL.

$stmt->bindValue(1, empty($post_data['name']) ? NULL : $post_data['name']);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.