Data doesn't get inserted into the database because it doesn't pass the if-statements. I am currently making a form to insert polls and corresponding answers into the database. Apparently the variables in the if-statements are non-countable objects (e.g. $answers
, $rows
. How do I make these countable, do I have to make them arrays? Or do I have to completely change the if-statements? These statements are going wrong:
if (count($answers) <= 1)
if (count($rows) == 0)
foreach($answers as $answer)
Here is my code:
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
// get form data and escape it properly
$poll = strip_tags($_POST["poll"]);
$rawAnswers = strip_tags($_POST["answers"]);
//
$formattedAnswers = str_replace(", ", ",", $rawAnswers);
$answers = explode(",", $formattedAnswers);
// add answers to database
include("opendb.php");
if (count($answers) <= 1) {
echo "<p>It makes no sense to add less than or equal to one answer.</p>";
} else {
// add poll to database if it is not already there
$pollNewCheck = $db->prepare('SELECT * FROM polls WHERE poll = ?');
$pollNewCheck->bindValue(1, $poll, PDO::PARAM_STR);
$pollNewCheck->execute();
$rows = $pollNewCheck->fetch();
if (count($rows) == 0) {
$pollQuery = $db->prepare('INSERT INTO polls (poll) VALUES ( ? )');
$pollQuery->bindValue(1, $poll, PDO::PARAM_STR);
$pollQuery->execute();
echo "<h2>Poll added!</h2><p id=\"addedPoll\">$poll</p>";
} else {
echo "<h2>Existing poll!</h2><p id=\"addedPoll\">\"$poll\" is already in the database. The answers you entered have been added to it.</p>";
}
// get poll_id for added poll
$pollIDQuery = $db->prepare('SELECT * FROM polls WHERE poll = ?');
$pollIDQuery->bindValue(1, $poll, PDO::PARAM_STR);
$pollIDQuery->execute();
$row = $pollIDQuery->fetch();
$pollID = $row[0];
echo "<h3>These are the available answers you added:</h3>";
echo "<ul>";
foreach($answers as $answer) {
$answerQuery = $db->prepare('INSERT INTO answers (answer, poll_id) VALUES ( ?, ? )');
$answerQuery->bindValue(1, $answer, PDO::PARAM_STR);
$answerQuery->bindValue(2, $pollID, PDO::PARAM_STR);
$answerQuery->execute();
echo "<li>$answer</li>";
}
echo "</ul>";
echo "<p id=\"returnToPanel\"><a href=\"/admin.php\">Return to admin panel</a></p>";
}
}
Aucun commentaire:
Enregistrer un commentaire