请用php写一个考试系统
时间: 2024-05-10 22:14:46 浏览: 111
php考试系统
3星 · 编辑精心推荐
好的,以下是一个简单的考试系统的PHP代码示例:
首先是数据库设计,考试系统需要至少两个表:users和questions。
users表用于存储考生的信息,包括姓名、邮箱、密码等。
questions表用于存储考试题目及答案。
下面是数据库表的结构:
```sql
CREATE TABLE `users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) NOT NULL,
`email` varchar(255) NOT NULL,
`password` varchar(255) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
CREATE TABLE `questions` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`question` varchar(255) NOT NULL,
`option1` varchar(255) NOT NULL,
`option2` varchar(255) NOT NULL,
`option3` varchar(255) NOT NULL,
`option4` varchar(255) NOT NULL,
`answer` int(11) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
```
然后是PHP代码,以下是简单的考试系统的PHP代码示例:
```php
<?php
//连接数据库
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "dbname";
$conn = mysqli_connect($servername, $username, $password, $dbname);
//检查连接是否成功
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
//登录功能
if (isset($_POST['login'])) {
$email = $_POST['email'];
$password = $_POST['password'];
$sql = "SELECT * FROM users WHERE email='$email' AND password='$password'";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) == 1) {
session_start();
$_SESSION['email'] = $email;
header('location: exam.php');
} else {
echo "Invalid email or password";
}
}
//考试功能
if (isset($_POST['submit'])) {
$score = 0;
$answers = $_POST['answers'];
foreach ($answers as $key => $value) {
$sql = "SELECT * FROM questions WHERE id='$key' AND answer='$value'";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) == 1) {
$score++;
}
}
echo "Your score is: " . $score;
}
//显示登录表单
if (!isset($_SESSION['email'])) {
?>
<form method="post">
<label>Email:</label>
<input type="email" name="email"><br>
<label>Password:</label>
<input type="password" name="password"><br>
<input type="submit" name="login" value="Login">
</form>
<?php
}
//显示考试题目
if (isset($_SESSION['email'])) {
$sql = "SELECT * FROM questions";
$result = mysqli_query($conn, $sql);
?>
<form method="post">
<?php
while ($row = mysqli_fetch_assoc($result)) {
?>
<p><?php echo $row['question']; ?></p>
<input type="radio" name="answers[<?php echo $row['id']; ?>]" value="1"> <?php echo $row['option1']; ?><br>
<input type="radio" name="answers[<?php echo $row['id']; ?>]" value="2"> <?php echo $row['option2']; ?><br>
<input type="radio" name="answers[<?php echo $row['id']; ?>]" value="3"> <?php echo $row['option3']; ?><br>
<input type="radio" name="answers[<?php echo $row['id']; ?>]" value="4"> <?php echo $row['option4']; ?><br>
<?php
}
?>
<input type="submit" name="submit" value="Submit">
</form>
<?php
}
//关闭数据库连接
mysqli_close($conn);
?>
```
此代码包含登录和考试功能,它首先连接到数据库,如果没有登录,则显示登录表单。如果已经登录,则显示考试题目。考生可以选择题目答案并提交,然后系统将计算分数并显示在屏幕上。
请注意,此处的代码仅供参考,实际使用中需要进行适当的修改和完善。
阅读全文