【问题标题】:Error in Passing Data in View in CodeIgniterCodeIgniter 在视图中传递数据时出错
【发布时间】:2015-01-03 15:20:39
【问题描述】:

我将 SQL 查询结果存储在 $data 变量中,然后从我的模型中将其传递给 search_view

        $this->db->like('LOWER(title)', strtolower($query));
        $q = $this->db->get('questions');
        $data = $q->row_array();
        $this->load->view('search_view', array('data' => $data));

我正在尝试使用以下结构在我的视图中显示所有结果:

<?php if ($data['search_type'] == 'question') { 
        foreach ($data as $question) {
?>


<div class="question-result">
    <h2><?php echo $question['title']; ?></h2>
    <p>Posted by: <a href="#"><?php echo $question['username']; ?>username</a></p>
    <p>Date Posted: <?php echo $question['date']; ?></p>
</div>


<?php } } ?>

我需要检查 $data['search_type'] 以查看执行了哪种类型的搜索,此位经过测试并且工作正常,但无需担心

我使用的所有变量(如用户名、标题和日期)都出现非法字符串偏移错误。

eddit* 示例转储:

array(7) { ["question_id"]=> string(1) "3" ["title"]=> string(19) "First Question Ever" ["content"]=> string(13) "Hello Content" ["date"]=> string(19) "2015-01-03 15:08:30" ["user_id"]=> string(2) "14" ["username"]=> string(4) "Ilya" ["search_type"]=> string(8) "question" } 

由于某种原因,这不会返回一个以上的问题,尽管执行的搜索应该有更多问题。

【问题讨论】:

  • 在你的 sn-p 前面加上 var_dump($data); 看看你实际得到了什么。

标签: php html arrays codeigniter


【解决方案1】:

您不需要使用另一个 foreach,因为它不再位于另一个维度。一旦你使用了-&gt;row_array(),只会返回一行。

<?php if ($data['search_type'] == 'question') { ?>

<div class="question-result">
    <h2><?php echo $data['title']; ?></h2>
    <p>Posted by: <a href="#"><?php echo $data['username']; ?>username</a></p>
    <p>Date Posted: <?php echo $data['date']; ?></p>
</div>

<?php } ?>

如果您希望获得更多结果,请改用-&gt;result_array()

$data = $q->result_array();

然后在查看:

<?php foreach ($data as $question): ?>
    <?php if ($question['search_type'] == 'question') { ?>
        <div class="question-result">
            <h2><?php echo $question['title']; ?></h2>
            <p>Posted by: <a href="#"><?php echo $question['username']; ?>username</a></p>
            <p>Date Posted: <?php echo $question['date']; ?></p>
        </div>
    <?php endif; ?>
<?php endforeach; ?>

或者也可以只添加$this-&gt;db-&gt;where('search_type', 'question'),这样您就不必在上述循环的 foreach 中放置 if。

【讨论】:

  • 修复了我只得到一个结果的问题,现在我可以看到两个结果并且格式正确,但是之后我仍然得到错误:/
  • @Ilya 您能否详细说明这些错误,哪些有效,哪些无效? however after that I still get the errors :/ 我很难猜到 :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多