以下是一个简单的PHP问卷调查系统的代码示例:

index.php:

<?php
session_start();

if(isset($_SESSION['completed']) && $_SESSION['completed'] === true) {
  header("Location: results.php");
  exit();
}

$questions = array(
  "What is your favorite color?",
  "What is your favorite food?",
  "What is your favorite animal?"
);

if(isset($_POST['submit'])) {
  $answers = array();
  foreach($questions as $q) {
    $answers[] = $_POST[str_replace(' ', '_', strtolower($q))];
  }
  $_SESSION['answers'] = $answers;
  $_SESSION['completed'] = true;
  header("Location: results.php");
  exit();
}
?>
<!DOCTYPE html>
<html>
<head>
  <title>Survey</title>
</head>
<body>
  <form method="POST">
    <?php foreach($questions as $q): ?>
      <label for="<?php echo str_replace(' ', '_', strtolower($q)); ?>"><?php echo $q; ?></label><br>
      <input type="text" name="<?php echo str_replace(' ', '_', strtolower($q)); ?>"><br><br>
    <?php endforeach; ?>
    <input type="submit" name="submit" value="Submit">
  </form>
</body>
</html>

results.php:

<?php
session_start();

if(isset($_SESSION['completed']) && $_SESSION['completed'] === false) {
  header("Location: index.php");
  exit();
}

$questions = array(
  "What is your favorite color?",
  "What is your favorite food?",
  "What is your favorite animal?"
);
$answers = $_SESSION['answers'];
?>
<!DOCTYPE html>
<html>
<head>
  <title>Survey Results</title>
</head>
<body>
  <h2>Survey Results</h2>
  <table>
    <tr>
      <th>Question</th>
      <th>Answer</th>
    </tr>
    <?php for($i=0; $i<count($questions); $i++): ?>
      <tr>
        <td><?php echo $questions[$i]; ?></td>
        <td><?php echo $answers[$i]; ?></td>
      </tr>
    <?php endfor; ?>
  </table>
</body>
</html>

这个问卷调查系统包含两个页面:index.php和results.php。index.php用于收集用户输入的答案,而results.php用于显示调查结果。

在index.php中,我们使用一个$questions数组来保存所有问题。在HTML表单中,我们使用一个foreach循环来动态生成每个问题的输入字段。我们使用str_replace和strtolower函数来生成每个字段的名称,以便在提交表单时将其与答案相关联。

在提交表单时,我们将所有答案保存在$answers数组中,然后将其存储在$_SESSION变量中。我们还将$_SESSION['completed']设置为true,以便在用户完成调查后,他们将被重定向到results.php页面。我们使用header函数来执行重定向。

在results.php页面上,我们检查$_SESSION['completed']是否为true,并且如果不是,则将用户重定向回index.php。否则,我们显示调查结果,包括每个问题和用户的回答。我们使用一个循环来遍历$questions和$answers数组,并将它们显示在一个HTML表格中。

注意,这个问卷调查系统非常简单,并且仅用于演示目的。在实际应用中,您可能需要更多的数据验证和安全性检查。

编程简单的PHP问卷调查系统

原文地址: https://www.cveoy.top/t/topic/CtU 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录