Displaying one row of sql query result in view

In my opinion, I am trying to display only one username user_username at the top of the page, and then all messages and message time below. I have no problem with the part foreach($message as $row), and it displays correctly. However, I cannot get Messages by <?php echo $message['user_username']; ?>to display the name of the message poster. Any help on how I can do this would be greatly appreciated.

View

<html>
<head>
    <title> View Messages </title>
</head>

<body>
    Messages by <?php echo $message['user_username']; ?>: 

    <?php foreach($message as $row){?>
        <?php echo $row->text;?>
        <br>
        <?php echo $row->posted_at;?>
        <br><br>
    <?php }?>
</body>
</html>

controller

<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class User extends CI_Controller {

public function view($name){

    //Error reporting if no name entered in url
    if ($name == NULL) {
        echo "no name entered in url";
        return;
    } else {
        $this->load->model('messages_model');
        $message['message'] = $this->messages_model->getMessagesByPoster($name);
        $this->load->view('ViewMessages',$message);
    }
}
}

Model

 <?php
 class Messages_model extends CI_Model {


public function __construct() {
    parent::__construct();
    $this->load->database();
}

//Return all messages posted by user with specified username
public function getMessagesByPoster($name) {
    $sql = "SELECT user_username, text, posted_at FROM Messages WHERE user_username = ?;";
    $query = $this->db->query($sql, $name);
    return $query->result();
}
}
+4
source share
2 answers

try it

Messages by <?php echo $message[0]['user_username']; ?>
                                ^

Bcz your array always creates a null index array

and your model should be

return $query->result_array();
+3
source

,

public function getMessagesByPoster($name) {
    $sql = "SELECT user_username, text, posted_at FROM Messages WHERE user_username = ?;";
    $query = $this->db->query($sql, $name);
    return $query->row_array();
}

,

  • $query->result()
  • $query->result_array()
  • $query->row()
  • $query->row_array()

result() row() result , SQL 1 . row() . 1 .

_array , , array object.

_array -free, , ->. , $result->memberID.

[]. , $result['memberID'].

.

+3

Source: https://habr.com/ru/post/1660306/


All Articles