我目前正在开发一个私人消息系统。现在我正在对收件箱进行编码,并在我的消息表中放置了两行临时数据,以测试收件箱是否正常工作。
我正在尝试返回此查询为true的所有行:
<?php
class Messages_model extends CI_Model {
public function inbox()
{
$user_id = $this->session->userdata('user_id');
$username = $this->session->userdata('username');
return $this->db->query("SELECT * FROM messages WHERE to_id = $user_id AND to_user = '$username'"); //to_id = id of currently logged in and to_user = username
}
}
这是我的控制器。我目前只返回一行,即使应返回两行。我在db中创建了两行,其中to_id和to_user等于我的会话数据。所以他们都应该被归还,而不仅仅是一个。当我使用row_array时,返回第一行,如CI用户指南中所述。当我使用result_array()时,仍然只返回一行。
我想要做的是在html中创建一个表格,其中包含几列和每行标题的1行,例如主题,地位,日期。然后下面的行将是实际的主题数据和消息的状态。然后我想运行一个while或foreach循环,每次从收件箱的消息表返回一行时,它将回显该空行。
这是我的控制器:
<?php
class Messages extends Public_Controller {
public function __construct() {
parent::__construct();
$this->load->model('messages_model');
}
public function inbox()
{
$query = $this->messages_model->inbox(); // return from model which is basically a row from messages table
if ($query->num_rows() != 0) // if rows returned is equal to 1
{
foreach ($query->result_array() as $row) // give array variable the value row_array
// grab specific elements from row and assign to variables
$row['id'];
$row['to_id'];
$row['to_user'];
$row['from_id'];
$row['from_user'];
$row['time_sent'];
$row['subject'];
$row['message'];
$row['opened'];
$row['replied'];
$this->load->view('messages/inbox', $row);
}
else
{
echo "You have 0 messages in your inbox";
}
}
}
我希望我清楚地解释我正在尝试做什么。 提前谢谢。
答案 0 :(得分:2)
你似乎在for循环中缺少大括号:
foreach ($query->result_array() as $row) // give array variable the value row_array
{
// grab specific elements from row and assign to variables
$row['id'];
$row['to_id'];
$row['to_user'];
$row['from_id'];
$row['from_user'];
$row['time_sent'];
$row['subject'];
$row['message'];
$row['opened'];
$row['replied'];
}
for循环仅适用于第一行,除非用括号括起身体。
答案 1 :(得分:1)
首先,请记住我对CodeIgniter不太熟悉。但是,你的问题是非常通用的PHP:
foreach ($query->result_array() as $row) // give array variable the value row_array
// grab specific elements from row and assign to variables
$row['id'];
$row['to_id'];
$row['to_user'];
$row['from_id'];
$row['from_user'];
$row['time_sent'];
$row['subject'];
$row['message'];
$row['opened'];
$row['replied'];
$this->load->view('messages/inbox', $row);
}
每次遇到一行时,都会调用$this->load->view()
。我相信你应该只调用一次视图,包含你想传递的所有数据。你可能想做这样的事情:
$data = array();
foreach ($query->result_array() as $row) {
$data[] = array (
'id' => $row['id'],
'to_id' => $row['to_id'],
'to_user' => $row['to_user'],
'from_id' => $row['from_id'],
'from_user' => $row['from_user'],
'time_sent' => $row['time_sent'],
'subject' => $row['subject'],
'message' => $row['message'],
'opened' => $row['opened'],
'replied' => $row['replied']
);
}
$this->load->view('messages/inbox', $data);
然后,您需要在视图中处理多条消息。