PHP和CodeIgniter框架的新手。
我在database
中有一个问题,我可以正确保存答案。但是我很难保存分配的user_id
的答案,并在测试结束时将score
输出到user
。
如果答案正确,则会显示1/1
其他0/1
。有人可以帮助我吗?
**从表格user_login
开始,只需要id
,表格results
为this,表格exercises
为that。
这是我的Controller
:
class Home extends CI_Controller {
function __construct() {
parent::__construct();
$this->load->model('Exercise');
}
function exercise_demo() {
//get the exercise out of the database to give to
//the view so that it can be shown.
$this->load->model('Exercise');
//give this to the view in an array
$data = array();
$data['exercise'] = $this->Exercise->load_exercise('Geography', '2');
$this->load->view('exercise_demo', $data);
}
function storedemo() {
$answer = $this->input->post('answer');
$id = $this->input->post('exerciseid');
$this->load->model('Exercise');
$correct = $this->Exercise->check_answer($id, $answer);
//store this in a database table
$data = array(
'answer_given' => $this->input->post('answer'),
'exercise_id' => $this->input->post('exerciseid'),
'result_tf' => $correct,
'user_id' => '0'
);
//transfer data to model
$this->Exercise->insert_result($data);
} }
这是我的Model
:
class Exercise extends CI_Model {
function __construct() {
parent::__construct();
}
public function load_exercise($topic, $difficulty) {
return $this->db->get_where('exercises', array('topic' => $topic, 'difficulty' => $difficulty))->row();
}
function insert_result($data) {
$this->db->insert('results', $data);
$is_inserted = $this->db->affected_rows() > 0;
if ($is_inserted) {
echo 'Answer saved!';
} else {
echo 'Something went wrong. No insert ):';
}
}
public function check_answer($id, $answer) {
//get the exercise out of the db
$exercise = $this->db->get_where('exercises', array('id' => $id))->row();
return $exercise->solution == $answer ? '1' : '0';
}
}
这是我的观看exercise_demo
:
<div>
<form method="post" action="<?= base_url('index.php/home/storedemo') ?>" >
<div id ="exercise">
<?= $exercise->exercise ?>
</div>
<input type ="hidden" name ="exerciseid" value="<?= $exercise->id ?>">
<input type="submit">
<br />
<br />
<h3> SCORE: </h3>
<div id="result">
<h3><?= $result ?> / 1 </h3> (comment this out to work properly)
</div>
</form>
</div>
</html>
答案 0 :(得分:0)
让我们从头到尾工作。
函数storedemo
获取已发布的答案
它会将其发送给check_answer
,以确定它是否正确。
check_answer
返回字符串&#39;正确&#39;如果是真的且不正确&#39;如果不对。
storedemo
然后使用insert_result
将check_answer
返回到数据库列result_tf
result_tf
是一个小小的int。您正在尝试将字符串传递到int列。这绝对不会起作用。
让check_answer
返回整数1或0而不是字符串&#39;正确&#39;或者&#39;不正确&#39;这将允许您将其插入result_tf
如果您的代码仍然没有给出预期的结果,那么因为还有其他问题。如果是这样,请自行调试一段时间,因为如果你在一段时间后仍然完全迷失了,我建议你发一个新问题。