I've been following a udemy course about object oriented php and wanted to improve the final result of the project.
We've create a shareboard where we display the shares of every user who posts one and I wanted to add in the shares page the user who posts the share.
Theres is two tables so far in the db one for the shares with a user_id to link with the user in the users table
Here's the current code:
The model:
class ShareModel extends Model{
public function Index(){
$this->query('SELECT * FROM shares ORDER BY create_date DESC');
$rows = $this->resultSet();
return $rows;
}
}
The view:
<div>
<?php if(isset($_SESSION['is_logged_in'])) : ?>
<a class="btn btn-success btn-share" href="<?php echo ROOT_PATH; ?>shares/add">Share Something</a>
<?php endif; ?>
<?php foreach($viewmodel as $item) : ?>
<div class="well">
<h3><?php echo $item['title']; ?></h3>
<small><?php echo $item['create_date']; ?></small>
<hr />
<p><?php echo $item['body']; ?></p>
<small><?php echo $item['user_id']; ?></small>
<br /><br />
<a class="btn btn-default" href="<?php echo $item['link']; ?>" target="_blank">Go To Website</a>
</div>
<?php endforeach; ?>
</div>
I know in the model I need to change the index like this:
class ShareModel extends Model{
public function Index(){
$query1 = $this->query('SELECT * FROM shares ORDER BY create_date DESC');
$query2 = $this->query('SELECT shares.id, users.name FROM shares INNER JOIN Users ON shares.user_id = users.id');
return array($query1, $query2);
}
}
But how can I access this in the view to display the content of the sahre and the name of the user?
As per my understanding, in view file,print_r() the $viewmodel
. $viewmodel[0]
will return the result set of 1st query & $viewmodel[1]
will return the resultset of 2nd.
Also why you want to write the 2 queries? Write single one like :
SELECT shares.id,shares.*, users.name
FROM shares
INNER JOIN Users ON shares.user_id = users.id
ORDER BY create_date DESC
You're not calling $this->resultSet()
after each query.
public function Index(){
$query1 = $this->query('SELECT * FROM shares ORDER BY create_date DESC');
$result1 = $this->resultSet();
$query2 = $this->query('SELECT shares.id, users.name FROM shares INNER JOIN Users ON shares.user_id = users.id');
$result2 = $this->resultSet();
return array($result1, $result2);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.