数据没有插入到数据库中,因为它没有传递if语句。我目前正在制作一个表格,将民意调查和相应的答案插入数据库。显然,if语句中的变量是不可数对象(例如$answers
,$rows
。如何使这些变量可数,我是否必须使它们成为数组?或者我必须完全改变它if-statements?这些陈述是错误的:
if (count($answers) <= 1)
if (count($rows) == 0)
foreach($answers as $answer)
这是我的代码:
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>";
}
}
答案 0 :(得分:0)
当您提供更多信息时,我会在此答案中添加更多内容。
这将解决您的问题:
print_r($_POST);
假设$ _POST [“answers”]包含“aaaa,bbbbb,cccc”,那么爆炸将起作用。由于您没有提供样本输入,因此无法确切知道。
$rawAnswers = strip_tags($_POST["answers"]); // Don't know what is in here
$formattedAnswers = str_replace(", ", ",", $rawAnswers);
$answers = explode(",", $formattedAnswers);
如果没有找到数据,PDOStatement :: fetch返回null或false。因此,这样做:
$row = $pollNewCheck->fetch();
if ( empty($row) ) {
// poll was not found in the database
} else {
// poll was found in the database
}
将prepare
移出循环。
$answerQuery = $db->prepare('INSERT INTO answers (answer, poll_id) VALUES ( ?, ? )');
foreach($answers as $answer) {
$answerQuery->bindValue(1, $answer, PDO::PARAM_STR);
$answerQuery->bindValue(2, $pollID, PDO::PARAM_STR);
$answerQuery->execute();
echo "<li>$answer</li>";
}