我正在 Codeigniter 中构建一个简单的测验应用程序,其中向用户展示一张图像,让他们猜测它是对还是错。类似于“热与否”。
有 25 个问题,全部回答是或否。我可以选择创建 25 个页面并在隐藏字段中保留以前的结果,但这似乎有点冗长和愚蠢。
我有一个视图文件,其中唯一改变的是图像。所以我想我可以将图像路径作为变量传递并动态更改它,但我无法在更抽象的级别上计算出如何记录每个答案的结果,然后在最后显示结果并插入数据库。
我遇到的问题是如何加载序列中的下一个图像并记录该结果。
P.s
图像将始终保持相同的顺序。它们是否是随机的并不重要,尽管那会很好!
您可以通过使用以下字段在数据库中插入问题来实现这一点:
ID - 问题的 ID。
图像 - 此问题的图像名称,例如“question1Image.jpg”
正确答案 - 此问题的正确答案,如果答案均为是/否,则可以使用 INT。 1 表示是,0 表示否。
现在您对数据库有疑问,在控制器上 e 可能会创建如下内容:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Quizz extends CI_Controller {
public function questions($idquestion){
$this->load->model('questions_model');
//fetch the questions from the database
$questions = $this->questions_model->get_questions();
//if it's a post we'll check if the answer is correct and pass the next question to the view
if($this->input->post()){
$answered_question = $this->questions_model->get_question($idquestion-1);
$question = $this->questions_model->get_question($idquestion);
if($answered_question['correct_answer']==$this->input->post('answer')){
//if the user answered correctly do something here
}
$data['question'] = $question;
//the id of the next question you'll use it for the next post
$data['next_question'] = $idquestion+1;
$this->load->view('your_view', $data);
}
//it's the first time the user uses this so we'll load the first answer
else{
$question = $this->questions_model->get_question(1);
$data['question'] = $question;
//the id of the next question you'll use it for the next post
$data['next_question'] = 2;
$this->load->view('your_view', $data);
}
}
}
在你看来,你可以有这样的东西:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Question page</title>
</head>
<body>
<?php //we'll use the codeigniter form helper to generate manually the form
echo form_open('quizz/questions/'.$next_question); ?>
<!-- This will load the image dynamically-->
<img src="<?=base_url('public/images/'.$question['image'])?>">
<label><input type="radio" name="answer" value="1">YES</label>
<label><input type="radio" name="answer" value="0">NO</label>
<button type="submit" >Submit</button>
<?=form_close();?>
</body>
</html>
该模型:
<?php
class questions_model extends CI_Model {
public function __construct()
{
$this->load->database();
}
public function get_questions()
{
return $this->db->get('questions_table')->result_array();
}
public function get_question($idquestion)
{
$this->db->select('questions_table.*');
$this->db->from('questions_table');
$this->db->where('questions_table.id', $idquestion);
return $this->db->get()->result_array();
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)