Здравствуйте, сделал систему голосования, нужно к определённому ответу добавить коммент, работает только голосование но комментарии не заносят я в базу. Помогите советом кодом, я смотрел параметры что отсылает я в post и все нормально отпровляет но не записывает в таблицу. Имеится код для голосования PHP: system mysql php php Helmp me please I try this code, bad commnet dont insert in table of comment. <?php include 'functions.php'; // Connect to MySQL $pdo = pdo_connect_mysql(); // If the GET request "id" exists (poll id)... if (isset($_GET['id'])) { // MySQL query that selects the poll records by the GET request "id" $stmt = $pdo->prepare('SELECT * FROM polls WHERE id = ?'); $stmt->execute([$_GET['id']]); // Fetch the record $poll = $stmt->fetch(PDO::FETCH_ASSOC); // Check if the poll record exists with the id specified if ($poll) { // MySQL query that selects all the poll answers $stmt = $pdo->prepare('SELECT * FROM poll_answers WHERE poll_id = ?'); $answer_id = $stmt->execute([$_GET['id']]); // Fetch all the poll anwsers $poll_answers = $stmt->fetchAll(PDO::FETCH_ASSOC); // If the user clicked the "Vote" button... if (isset($_POST['poll_answer'])) { // Update and increase the vote for the answer the user voted for $stmt = $pdo->prepare('UPDATE poll_answers SET votes = votes + 1 WHERE id = ?'); $stmt->execute([$_POST['poll_answer']]); if(isset($poll_id) & isset($title) & isset($comment)){ $poll_id = $_POST["poll_id"]; $title = $_POST["title"]; $comment = $_POST["comment"]; mysql_query("INSERT INTO poll_comment VALUES (Null,$poll_id,$title,$comment)"); //mysql_query("INSERT INTO poll_comment (poll_id,title,comment) VALUES ('','$poll_id','$title','comment')"); //$stmt->execute([$_POST['poll_comment']]); // Redirect user to the result page header ('Location: result.php?id=' . $_GET['id']); exit; } } } else { die ('Poll with that ID does not exist.'); } } else { die ('No poll ID specified.'); } // Update and increase the vote for the answer the user voted for //$stmt = $pdo->prepare("INSERT INTO poll_comment VALUES (Null,$poll_id,$title,$comment)"); // $stmt->execute([$_POST['poll_comment']]); ?> <?=template_header('Poll Vote')?> <div class="content poll-vote"> <h2><?=$poll['title']?></h2> <p><?=$poll['desc']?></p> <form action="vote.php?id=<?=$_GET['id']?>" method="post"> <?php for ($i = 0; $i < count($poll_answers); $i++): ?> <label> <input type="radio" name="poll_answer" value="<?=$poll_answers[$i]['id']?>"<?=$i == 0 ? ' checked' : ''?>> <?=$poll_answers[$i]['title']?> </label> <input type="hidden" name="poll_id" value=<?=$_GET['id']?>> <?php endfor; ?> <div> <tr> <td> title : </td><td><input type="text" name="title"></td> </tr> <tr> <td> Comment : </td><td><textarea name="comment" rows="6" cols="50"></textarea></td> </tr> <? ?> <input type="submit" value="Vote"> <a href="result.php?id=<?=$poll['id']?>">View Result</a> </div> </form> </div> И таблица комментариев Код (Text): CREATE TABLE IF NOT EXISTS `poll_comment` ( `id` int(11) NOT NULL AUTO_INCREMENT, `poll_id` int(11) NOT NULL, `title` text NOT NULL, `comment` text(256) NOT NULL , PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;
Переделал код но не работает Даже если сделаю так $stmt = $pdo->prepare("INSERT INTO poll_comment (poll_id,title,comment) VALUES ('$poll_id','$title','$comment')"); $stmt->execute([$_POST['poll_comment ']]); Код (Text): ?php include 'functions.php'; // Connect to MySQL $pdo = pdo_connect_mysql(); // If the GET request "id" exists (poll id)... if (isset($_GET['id'])) { // MySQL query that selects the poll records by the GET request "id" $stmt = $pdo->prepare('SELECT * FROM polls WHERE id = ?'); $stmt->execute([$_GET['id']]); // Fetch the record $poll = $stmt->fetch(PDO::FETCH_ASSOC); // Check if the poll record exists with the id specified if ($poll) { // MySQL query that selects all the poll answers $stmt = $pdo->prepare('SELECT * FROM poll_answers WHERE poll_id = ?'); $answer_id = $stmt->execute([$_GET['id']]); // Fetch all the poll anwsers $poll_answers = $stmt->fetchAll(PDO::FETCH_ASSOC); // If the user clicked the "Vote" button... if (isset($_POST['poll_answer'])) { // Update and increase the vote for the answer the user voted for $stmt = $pdo->prepare('UPDATE poll_answers SET votes = votes + 1 WHERE id = ?'); $stmt->execute([$_POST['poll_answer']]); if(isset($_POST["submit"])) { //$name = $_POST["name"]; $email = $_POST["poll_id"]; $website = $_POST["title"]; $comment = $_POST["comment"]; mysql_query("INSERT INTO poll_comment (poll_id,title,comment) VALUES ('$poll_id','$title','$comment')"); //$stmt->execute([$_POST['poll_comment']]); // Redirect user to the result page header ('Location: result.php?id=' . $_GET['id']); exit; } } } else { die ('Poll with that ID does not exist.'); } } else { die ('No poll ID specified.'); } ?> <?=template_header('Poll Vote')?> <div class="content poll-vote"> <h2><?=$poll['title']?></h2> <p><?=$poll['desc']?></p> <form action="vote.php?id=<?=$_GET['id']?>" method="post"> <?php for ($i = 0; $i < count($poll_answers); $i++): ?> <label> <input type="radio" name="poll_answer" value="<?=$poll_answers[$i]['id']?>"<?=$i == 0 ? ' checked' : ''?>> <?=$poll_answers[$i]['title']?> </label> <?php endfor; ?> <div> <input type="hidden" name="poll_id" value=<?=$_GET['id']?>> <tr> <td> title : </td><td><input type="text" name="title"></td> </tr> <tr> <td> Comment : </td><td><textarea name="comment" rows="6" cols="50"></textarea></td> </tr> <? ?> <input type="submit" value="Vote"> <a href="result.php?id=<?=$poll['id']?>">View Result</a> </div> </form> </div>
вместо 33 строки пропиши var_dump ( $_POST ); и смотри результат запроса, пришел ? Значит используй INSERT с правильным синтаксисом инструмента. - если нет, то выясняй - почему не дошел до var_dump --- Добавлено --- 36 строку закоментируй, ибо перенаправлять при дебаге будет
Если я сюда Код (Text): mysql_query("INSERT INTO poll_comment (poll_id,title,comment) VALUES ('$poll_id','$title','$comment')") вставляю сразу данные то есть без переменных $poll_id','$title','$comment то записывается все нормально, как только я вставляю в запрос переменные то у меня данные не берутся с формы Код (Text): <?php endfor; ?> <div> <input type="hidden" name="poll_id" value=<?=$_GET['id']?>> <tr> <td> title : </td><td><input type="text" name="title"></td> </tr> <tr> <td> Comment : </td><td><textarea name="comment" rows="6" cols="50"></textarea></td> </tr>
@Lomanur, проверьте значения переменных на предмет наличия кавычек и апострофов. В общем - используйте не прямую вставку переменных в запрос, а подготовленные выражения.
ответ с кавычками array(4) { ["poll_answer"]=> string(1) "8" ["poll_id"]=> string(1) "2" ["title"]=> string(5) "fdfdf" ["comment"]=> string(4) "fdfd" }
Это $_POST? Тогда с кавычками всё в порядке. Теперь по поводу варианта с подготовленными выражениями из #4 Вот это вот: должно выглядеть так: PHP: $stmt = $pdo->prepare("INSERT INTO poll_comment (poll_id, `title`, `comment`) VALUES (?, ?, ?)"); $stmt->execute([$poll_id, $title, $comment]); И ещё не из кода в том-же #4 не понятно, откуда берётся $title. Соответственно, вариант с prepare() и execute() должен полностью заменить строку 33 (из #4, с mysql_query()).