我尝试使用网站提供的教程学习CodeIgniter框架,我对php非常陌生,我可能会问一个愚蠢的问题。 我尝试将复选框状态值从视图传递到控制器(是否选中复选框的状态(,它显示在错误消息之后。
遇到 PHP 错误
严重性:警告
消息:为 foreach(( 提供的参数无效
文件名:控制器/待办事项.php
行号:29
当我在控制器中跟踪时,这是由于foreach循环初始化。然后我附和
echo $completed_todos;
echo $completed_todos[0];
echo $completed_todos[1]; — No value;
我认为的是,它不会将所有复选框值传递给控制器。
在视图中,我使用了以下代码: (索引.php(
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Simple CodeIgniter App - Todos</title>
<link rel="stylesheet"
href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
</head>
<body>
<div class="container">
<?php echo form_open('todos/update_completed'); ?>
<h1>Todos</h1>
<div class="list-group">
<?php foreach ($todos as $todo) { ?>
<div class="list-group-item clearfix">
<?php
echo form_checkbox('completed', $todo->id, $todo->completed);
?>
<?php echo $todo->task; ?>
</div>
在控制器中,我使用了以下代码
待办事项控制器代码
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Todos extends CI_Controller {
public function __construct() {
parent::__construct();
// Load the todo model to make it available
// to *all* of the controller's actions
$this->load->model('Todo_model');
$this->load->helper('form');
}
public function update_completed() {
$completed_todos = $this->input->post('completed');
echo $completed_todos;
foreach ($completed_todos as $todo_id) {
echo 'The todo with id = ' . $todo_id
. ' is marked as completed.<br>';
}
}
在这里你想获取多个复选框的值,所以你需要输入一个数组。但是您已经尝试了简单的字符串并在foreach循环中使用它,这就是它给出错误的原因。
请检查下面的代码。
索引.php (查看文件(
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Simple CodeIgniter App - Todos</title>
<link rel="stylesheet"
href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
</head>
<body>
<div class="container">
<h1>Todos</h1>
<?php echo form_open('todos/update_completed'); ?>
<div class="list-group">
<?php foreach ($todos as $todo) { ?>
<div class="list-group-item clearfix">
<?php echo form_checkbox('completed[]', $todo->id, $todo->completed); ?>
<?php echo $todo->task; ?>
</div>
<?php } ?>
</div>
<button type="submit">Submit</button>
<?php echo form_close();
</div>
</body>
</html>
待办事项(控制器文件(
public function update_completed() {
$completed_todos = $this->input->post('completed');
// No need to echo $completed_todos. If you want then please do below line.
// var_dump($completed_todos);
foreach ($completed_todos as $todo_id) {
echo 'The todo with id = ' . $todo_id. ' is marked as completed.<br>';
}
}