Hi there, i have made a system where an admin can login and create a poll, the problem is even when no data is entered the poll is still being created, i want to prevent this. I have tried using if(empty but it doesn’t seem to work, any help would be appreciated. I apologise if this is not formatted correctly.
<?php
include 'functions.php';
$pdo = pdo_connect_mysql();
$msg = '';
// Check if POST data is not empty
if (!empty($_POST)) {
// Post data not empty insert a new record
// Check if POST variable "title" exists, if not default the value to blank, basically the same for all variables
$title = isset($_POST['title']) ? $_POST['title'] : '';
$desc = isset($_POST['desc']) ? $_POST['desc'] : '';
// Insert new record into the "polls" table
$stmt = $pdo->prepare('INSERT INTO polls VALUES (NULL, ?, ?)');
$stmt->execute([$title, $desc]);
// Below will get the last insert ID, this will be the poll id
$poll_id = $pdo->lastInsertId();
// Get the answers and convert the multiline string to an array, so we can add each answer to the "poll_answers" table
$answers = isset($_POST['answers']) ? explode(PHP_EOL, $_POST['answers']) : '';
foreach ($answers as $answer) {
// If the answer is empty there is no need to insert
if (empty($answer)) {
echo 'no entry';
} else {
echo 'continue';
}
// Add answer to the "poll_answers" table
$stmt = $pdo->prepare('INSERT INTO poll_answers VALUES (NULL, ?, ?, 0)');
$stmt->execute([$poll_id, $answer]);
}
// Output message
$msg = 'Created Successfully!';
}
?>