【问题标题】:Can access detailed information through URL with function parameters (Codeigniter)可以通过带有函数参数的 URL 访问详细信息(Codeigniter)
【发布时间】:2017-09-13 15:22:12
【问题描述】:

我正在为一个包含新闻的博客创建我的第一个 Codeigniter 应用程序。在主页上只有新闻的标题,它也是一个链接到一个视图的详细信息和新闻正文。我在通过 URL 访问 get 时遇到问题,该 URL 必须通过一个接收新 ID 作为参数的函数。我只是可以让它工作。有人可以帮我吗?

问题不在于函数本身,因为当我将静态值分配给 URL 时它工作正常,但由于某种原因,我可以将 $row->id 对象作为 Get 通过 URL 以正确的值发送每一条新闻。

型号

class Post extends CI_Model{


    public function getPost(){

        $this->load->database('fintech_blog');
        $data = $this->db->get('post');
        return $data->$result();

    }

控制器

public function getPost($id){

    $query = $this->db->query("select * from post where id = '$id' ");
    $rows = $query->result(); //method for putting into an array format
    $data=array('result'=>$rows);

    $this->load->view('view',$data);

}

查看

foreach ($result as $row): 

$id = $row->id;
$post = site_url('welcome/getPost/$row->id');

?>

<!-- Main Content -->
<div class="container">
    <div class="row">
        <div class="col-lg-8 col-md-10 mx-auto">
            <div class="post-preview">
                <a href="<?php echo $post; ?>">
                    <h2 class="post-title">
                        <?php echo $row->title; ?>
                    </h2>
                    <h3 class="post-subtitle">
                        <?php echo $row->calling; ?>
                    </h3>

                </a>
                <p class="post-meta">Posted on
                    <!-- <a href="#">Start Bootstrap</a> -->
                    <?php echo time_elapsed_string($row->created); ?></p>

                </div>
                <hr>

            </div>
        </div>
    </div>

<?php endforeach; ?>

【问题讨论】:

  • 在视图中,$post = site_url('welcome/getPost/$row->id');这里变量不会解析,因为使用了单引号('')。将单引号('')换成双引号(“”)再试试。
  • 你可以先试试这个$post = site_url('welcome/getPost/' . $row-&gt;id);确定

标签: php function codeigniter url parameters


【解决方案1】:

问题来自您为$post 创建字符串的方式。 正如一位评论者所说,问题在于使用单引号并改用双引号。双引号字符串最重要的特性是变量名会被扩展。这意味着变量符号(在这种情况下为$test)被替换为变量的值。

举例说明:

$test = "blue";
//first, a string created with single quotes
echo 'The sky is $test today.';  //outputs: The sky is $test today.

但是使用双引号来创建字符串...

echo "The sky is $test today.";  //outputs: The sky is blue today.

var $test 被扩展为它所持有的值。

所以,视图中foreach循环的前两行应该是。

 $id = $row->id;
 $post = site_url("welcome/getPost/$row->id");

但是,您从不使用$id,并且您只使用一次$post。这对我说,这两行是不需要的。将它们都删除。

换行

<a href="<?php echo $post; ?>">

<a href="<?php echo site_url("welcome/getPost/$row->id"); ?>">

【讨论】:

  • 非常感谢您的帮助@DFriend
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-11-10
  • 2018-07-31
  • 2018-05-12
相关资源
最近更新 更多