Search code examples
phpyii2yii2-advanced-appyii2-user

Yii2 - list every post - coding error


I am new in Yii2 and I made a site where i can write posts, view them, delete them etc...

I want to list every post from a DB on one page as a "timeline"

My code does not list any error simply just show the very first record only.

Here is my code from (views) index.php

        <?php

use yii\helpers\Html;
use yii\widgets\ListView;

/* @var $this yii\web\View */
/* @var $searchModel frontend\models\search\TweetSearch */
/* @var $dataProvider yii\data\ActiveDataProvider */

$this->title = 'My tweets';

?>
<div class="tweet-model-index">

    <h1 class="text-center"><?= Html::encode($this->title) ?></h1>


    <p class="text-center">
        <?= Html::a('New Tweet', ['create'], ['class' => 'btn btn-success']) ?>
    </p>

    <?php

    $con = \Yii::$app->db;

    $sql = $con->createCommand("SELECT * FROM tweet ORDER BY created_at DESC");

    $tweets = $sql->queryAll();

    if(!$tweets)
        echo '<h2> This is empty </h2>';
     else{
           foreach($tweets as $tweet){
       ?>



    <hr>
    <div class="container-fluid">
        <div class="col-md-8 col-md-offset-2">
            <h2 class="text-left">
                <?php echo $tweet['tweet_title']; ?> 
                <br><small>Author: <b><?php echo $tweet['author_id'];?> </b>Created at: <b><?php echo date(($tweet['created_at']));?></b>
                    <br>Updated at: <b><?php echo date(($tweet['updated_at']));?>
                </small>
            </h2>

                <p class="text-left">
                <?= Html::a('Update', ['update', 'id' => $tweet['tweet_id']], ['class' => 'btn btn-primary']) ?>
                <?= Html::a('View', ['view', 'id' => $tweet['tweet_id']], ['class' => 'btn btn-primary']) ?>
                <?= Html::a('Delete', ['delete', 'id' => $tweet['tweet_id']], [
                                        'class' => 'btn btn-danger',
                                        'data' => [
                                        'confirm' => 'Are you sure you want to delete this item?',
                                        'method' => 'post',
                                        ],
                                    ]) ?>
                </p>



        </div>


    </div>

</div>
<?php endforeach; ?>
<?php endif; ?>

May i ask You guys, how can I count the views on each post?

I tried this on my TweetController but doesn't work.

public function actionView($id)
{
    $this->render('view',array(
        'model'=>$this->loadModel($id));
}

Solution

  • Start using braces!

    else
        foreach($tweets as $tweet);
    ?>
    

    to this:

    else {
        foreach($tweets as $tweet) {
    ?>
    

    or even better in VIEWS:

    else:
        foreach($tweets as $tweet):
    ?>
    
    .....
    .....
    
    <?php endforeach; ?>
    <?php endif; ?>