Intereting Posts
Обновить DOM с помощью jquery после вызова AJAX PHP 5.6 с Mysqli_connect Что означает \ d + в терминах регулярного выражения? Убить Active Session, если пользователь заблокирован Лучший способ получить файлы из каталога, отфильтрованного определенным расширением в php Дерево FuelUX: как установить источник данных с источником json? Laravel: проблема UTF-8 при экспорте CSV MySQL исправляет пробелы автоинкремента в двух таблицах Использование PHP substr () и strip_tags () при сохранении форматирования и без нарушения HTML PhpStorm Выбрасывает ошибку для phpcs Facebook PHP SDK – Пользователь по-прежнему отображается как зарегистрированный в веб-приложении, хотя выходил из Facebook PHP MySQL PDO TextArea Где условие с проверкой состояния Как обновить веб-страницу без перезагрузки веб-страницы с помощью AJAX? динамический анализ токенов как вернуть mysql в качестве массива массивов в json, используя php

Yii: Как получить несколько данных из db

Я ibibie. Я пытаюсь получить данные из базы данных на первую страницу. Имя таблицы – это story и я хочу получить название и историю из таблицы. Для этого я сделал файл allstory.php файле my view и создал функцию allstory() в моем storycontroller . Это код для моего контроллера.

 <?php class StoryController extends RController { /** * @var string the default layout for the views. Defaults to '//layouts/column2', meaning * using two-column layout. See 'protected/views/layouts/column2.php'. */ public $layout='//layouts/admin'; /** * @return array action filters */ public function filters() { return array( // 'accessControl', // perform access control for CRUD operations // 'postOnly + delete', // we only allow deletion via POST request 'rights', ); } /** * Specifies the access control rules. * This method is used by the 'accessControl' filter. * @return array access control rules */ public function accessRules() { return array( array('allow', // allow all users to perform 'index' and 'view' actions 'actions'=>array('index','view'), 'users'=>array('*'), ), array('allow', // allow authenticated user to perform 'create' and 'update' actions 'actions'=>array('create','update'), 'users'=>array('@'), ), array('allow', // allow admin user to perform 'admin' and 'delete' actions 'actions'=>array('admin','delete'), 'users'=>array('admin'), ), array('deny', // deny all users 'users'=>array('*'), ), ); } /** * Displays a particular model. * @param integer $id the ID of the model to be displayed */ public function actionView($id) { $this->render('view',array( 'model'=>$this->loadModel($id), )); } public function actionAllstory() //This has been added to view all the stories on the stories page { $this->layout='main'; $this->render('allstory'); } /** * Creates a new model. * If creation is successful, the browser will be redirected to the 'view' page. */ public function actionCreate() { $model=new Story; // Uncomment the following line if AJAX validation is needed // $this->performAjaxValidation($model); if(isset($_POST['Story'])) { $model->attributes=$_POST['Story']; if($model->save()) $this->redirect(array('view','id'=>$model->id)); } $this->render('create',array( 'model'=>$model, )); } /** * Updates a particular model. * If update is successful, the browser will be redirected to the 'view' page. * @param integer $id the ID of the model to be updated */ public function actionUpdate($id) { $model=$this->loadModel($id); // Uncomment the following line if AJAX validation is needed // $this->performAjaxValidation($model); if(isset($_POST['Story'])) { $model->attributes=$_POST['Story']; if($model->save()) $this->redirect(array('view','id'=>$model->id)); } $this->render('update',array( 'model'=>$model, )); } /** * Deletes a particular model. * If deletion is successful, the browser will be redirected to the 'admin' page. * @param integer $id the ID of the model to be deleted */ public function actionDelete($id) { if(Yii::app()->request->isPostRequest) { // we only allow deletion via POST request $this->loadModel($id)->delete(); // if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser if(!isset($_GET['ajax'])) $this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin')); } else throw new CHttpException(400,'Invalid request. Please do not repeat this request again.'); } /** * Lists all models. */ public function actionIndex() { $dataProvider=new CActiveDataProvider('Story'); $this->render('index',array( 'dataProvider'=>$dataProvider, )); } /** * Manages all models. */ public function actionAdmin() { $model=new Story('search'); $model->unsetAttributes(); // clear any default values if(isset($_GET['Story'])) $model->attributes=$_GET['Story']; $this->render('admin',array( 'model'=>$model, )); } /** * Returns the data model based on the primary key given in the GET variable. * If the data model is not found, an HTTP exception will be raised. * @param integer $id the ID of the model to be loaded * @return Story the loaded model * @throws CHttpException */ public function loadModel($id) { $model=Story::model()->findByPk($id); if($model===null) throw new CHttpException(404,'The requested page does not exist.'); return $model; } /** * Performs the AJAX validation. * @param Story $model the model to be validated */ protected function performAjaxValidation($model) { if(isset($_POST['ajax']) && $_POST['ajax']==='story-form') { echo CActiveForm::validate($model); Yii::app()->end(); } } } 

И это мой allstory.php файла вида

  <div class="content"> <div class="banner"> <img src="<?php echo Yii::app()->request->baseurl;?>/img/story-banner.jpg" class="img-responsive"> </div><!--banner ending here--><br> <div class="story-content"> <div class="row"> <div class="col-md-8 col-md-offset-2 vol-stories"> <div class="media"> <div class="media-left"> <a href="user-profile.php"> <?php $modelnew=$model->story; foreach($modelnew as $test) { ?> <img class="media-object" src="<?php echo Yii::app()->request->baseurl;?>/img/media.jpg"> </a> </div> <div class="media-body"><strong><?php echo $test->user->username;?></strong> <!--username will come here--> <h4 class="media-heading"><strong><br><br><?php echo $test->title?></strong></h4><!--title will come here--> <p><?php echo $test->story?></p><!--story will come here--> <?php } ?> </div> </div><!--Media ending here--> </div> </div><!--row ending here--><br> <hr> <div class="write-story"> <div class="row"> <div class="col-md-6 col-md-offset-3"><br> <form> <strong>Title:</strong><textarea class="form-control" rows="1"></textarea> </form> </div> </div><!--row ending here--> <div class="row"> <div class="col-md-6 col-md-offset-3"><br> <form> <strong>Story:</strong><textarea class="form-control" rows="3"></textarea> </form> </div> </div><!--row ending here--> <div class="row"> <div class="col-md-6 col-md-offset-3"><br> <button class="btn btn-primary">Share</button> </div> </div><br> </div><!--write-story ending here--> </div><!--content ending here--> </div><!--container ending here--> 

Это сюжетная модель

 <?php /** * This is the model class for table "story". * * The followings are the available columns in table 'story': * @property integer $id * @property string $title * @property string $story * @property integer $user_id * * The followings are the available model relations: * @property User $user */ class Story extends CActiveRecord { /** * Returns the static model of the specified AR class. * @param string $className active record class name. * @return Story the static model class */ public static function model($className=__CLASS__) { return parent::model($className); } /** * @return string the associated database table name */ public function tableName() { return 'story'; } /** * @return array validation rules for model attributes. */ public function rules() { // NOTE: you should only define rules for those attributes that // will receive user inputs. return array( array('title, story, user_id', 'required'), array('user_id', 'numerical', 'integerOnly'=>true), array('title', 'length', 'max'=>100), array('story', 'length', 'max'=>1000), // The following rule is used by search(). // Please remove those attributes that should not be searched. array('id, title, story, user_id', 'safe', 'on'=>'search'), ); } /** * @return array relational rules. */ public function relations() { // NOTE: you may need to adjust the relation name and the related // class name for the relations automatically generated below. return array( 'user' => array(self::BELONGS_TO, 'User', 'user_id'), ); } /** * @return array customized attribute labels (name=>label) */ public function attributeLabels() { return array( 'id' => 'ID', 'title' => 'Title', 'story' => 'Story', 'user_id' => 'User', ); } /** * Retrieves a list of models based on the current search/filter conditions. * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions. */ public function search() { // Warning: Please modify the following code to remove attributes that // should not be searched. $criteria=new CDbCriteria; $criteria->compare('id',$this->id); $criteria->compare('title',$this->title,true); $criteria->compare('story',$this->story,true); $criteria->compare('user_id',$this->user_id); return new CActiveDataProvider($this, array( 'criteria'=>$criteria, )); } } 

Это модель для профиля

 <?php /** * This is the model class for table "profiles". * * The followings are the available columns in table 'profiles': * @property integer $user_id * @property string $lastname * @property string $firstname * @property string $picture * * The followings are the available model relations: * @property User $user */ class Profiles extends CActiveRecord { /** * Returns the static model of the specified AR class. * @param string $className active record class name. * @return Profiles the static model class */ public static function model($className=__CLASS__) { return parent::model($className); } /** * @return string the associated database table name */ public function tableName() { return 'profiles'; } /** * @return array validation rules for model attributes. */ public function rules() { // NOTE: you should only define rules for those attributes that // will receive user inputs. return array( array('lastname, firstname', 'length', 'max'=>50), array('picture', 'length', 'max'=>500), // The following rule is used by search(). // Please remove those attributes that should not be searched. array('user_id, lastname, firstname, picture', 'safe', 'on'=>'search'), ); } /** * @return array relational rules. */ public function relations() { // NOTE: you may need to adjust the relation name and the related // class name for the relations automatically generated below. return array( 'user' => array(self::BELONGS_TO, 'User', 'user_id'), ); } /** * @return array customized attribute labels (name=>label) */ public function attributeLabels() { return array( 'user_id' => 'User', 'lastname' => 'Lastname', 'firstname' => 'Firstname', 'picture' => 'Picture', ); } /** * Retrieves a list of models based on the current search/filter conditions. * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions. */ public function search() { // Warning: Please modify the following code to remove attributes that // should not be searched. $criteria=new CDbCriteria; $criteria->compare('user_id',$this->user_id); $criteria->compare('lastname',$this->lastname,true); $criteria->compare('firstname',$this->firstname,true); $criteria->compare('picture',$this->picture,true); return new CActiveDataProvider($this, array( 'criteria'=>$criteria, )); } } 

И это модель для пользователя

 <?php /** * This is the model class for table "user". * * The followings are the available columns in table 'user': * @property integer $id * @property string $username * @property string $password * @property string $email * @property string $gender * @property string $activkey * @property string $create_at * @property string $lastvisit_at * @property integer $superuser * @property integer $status * @property string $salt * @property integer $requires_new_password * @property integer $login_attempts * @property integer $login_time * @property string $login_ip * @property string $activation_key * @property string $validation_key * @property string $create_time * @property string $update_time * @property string $reset_token * @property string $image * @property string $address * * The followings are the available model relations: * @property UserJoinEvent[] $userJoinEvents * @property UserRateReviewNgo[] $userRateReviewNgos * @property UserUploadVideo[] $userUploadVideos * @property UserWriteStory[] $userWriteStories * @property VolunteerForm[] $volunteerForms */ class User extends CActiveRecord { /** * Returns the static model of the specified AR class. * @param string $className active record class name. * @return User the static model class */ public static function model($className=__CLASS__) { return parent::model($className); } /** * @return string the associated database table name */ public function tableName() { return 'user'; } /** * @return array validation rules for model attributes. */ public function rules() { // NOTE: you should only define rules for those attributes that // will receive user inputs. return array( array('superuser, status, requires_new_password, login_attempts, login_time', 'numerical', 'integerOnly'=>true), array('username, login_ip, address', 'length', 'max'=>45), array('password, email, activkey, activation_key', 'length', 'max'=>120), array('gender', 'length', 'max'=>1), array('salt, validation_key', 'length', 'max'=>255), array('reset_token', 'length', 'max'=>250), array('image', 'length', 'max'=>450), array('create_at, lastvisit_at, create_time, update_time', 'safe'), // The following rule is used by search(). // Please remove those attributes that should not be searched. array('id, username, password, email, gender, activkey, create_at, lastvisit_at, superuser, status, salt, requires_new_password, login_attempts, login_time, login_ip, activation_key, validation_key, create_time, update_time, reset_token, image, address', 'safe', 'on'=>'search'), array('image', 'file','types'=>'jpg, gif, png', 'allowEmpty'=>true, 'on'=>'update'), //array('title, image', 'length', 'max'=>255, 'on'=>'insert,update'), ); } /** * @return array relational rules. */ public function relations() { // NOTE: you may need to adjust the relation name and the related // class name for the relations automatically generated below. return array( 'userJoinEvents' => array(self::HAS_MANY, 'UserJoinEvent', 'User_user_id'), 'userRateReviewNgos' => array(self::HAS_MANY, 'UserRateReviewNgo', 'User_user_id'), 'userUploadVideos' => array(self::HAS_MANY, 'UserUploadVideo', 'User_user_id'), 'userWriteStories' => array(self::HAS_MANY, 'UserWriteStory', 'User_user_id'), 'volunteerForms' => array(self::HAS_MANY, 'VolunteerForm', 'User_user_id'), //'profile' => array(self::BELONGS_TO, 'profile', 'id','through'=>'user'), ); } /** * @return array customized attribute labels (name=>label) */ public function attributeLabels() { return array( 'id' => 'ID', 'username' => 'Username', 'password' => 'Password', 'email' => 'Email', 'gender' => 'Gender', 'activkey' => 'Activkey', 'create_at' => 'Create At', 'lastvisit_at' => 'Lastvisit At', 'superuser' => 'Superuser', 'status' => 'Status', 'salt' => 'Salt', 'requires_new_password' => 'Requires New Password', 'login_attempts' => 'Login Attempts', 'login_time' => 'Login Time', 'login_ip' => 'Login Ip', 'activation_key' => 'Activation Key', 'validation_key' => 'Validation Key', 'create_time' => 'Create Time', 'update_time' => 'Update Time', 'reset_token' => 'Reset Token', 'image' => 'Image', 'address' => 'Address', ); } /** * Retrieves a list of models based on the current search/filter conditions. * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions. */ public function search() { // Warning: Please modify the following code to remove attributes that // should not be searched. $criteria=new CDbCriteria; $criteria->compare('id',$this->id); $criteria->compare('username',$this->username,true); $criteria->compare('password',$this->password,true); $criteria->compare('email',$this->email,true); $criteria->compare('gender',$this->gender,true); $criteria->compare('activkey',$this->activkey,true); $criteria->compare('create_at',$this->create_at,true); $criteria->compare('lastvisit_at',$this->lastvisit_at,true); $criteria->compare('superuser',$this->superuser); $criteria->compare('status',$this->status); $criteria->compare('salt',$this->salt,true); $criteria->compare('requires_new_password',$this->requires_new_password); $criteria->compare('login_attempts',$this->login_attempts); $criteria->compare('login_time',$this->login_time); $criteria->compare('login_ip',$this->login_ip,true); $criteria->compare('activation_key',$this->activation_key,true); $criteria->compare('validation_key',$this->validation_key,true); $criteria->compare('create_time',$this->create_time,true); $criteria->compare('update_time',$this->update_time,true); $criteria->compare('reset_token',$this->reset_token,true); $criteria->compare('image',$this->image,true); $criteria->compare('address',$this->address,true); return new CActiveDataProvider($this, array( 'criteria'=>$criteria, )); } } 

Я не могу получить результат, потому что у меня нет идеи, что я делаю это правильно или неправильно. Поскольку я использую этот код, он также дает мне ошибку, которая является Undefined variable: model

Related of "Yii: Как получить несколько данных из db"

Сначала у вас есть

  class StoryController extends RController 

почему вы расширяете RController, а не просто Controller?

то для контроллера, если вы хотите, чтобы один рассказ по id вам нужно, и действуйте так, как это

 public function actionSingleStory($id) //This has been added to view a single story { $model=$this->loadModel($id); $this->layout='main'; $this->render('singlestory', array('model'=>$model)); } 

и упрощенное представление (singlestory.php), подобное этому (я предполагаю, что у вас есть поле $ model-> story_title amd $ model-> story_text

 <div class="content"> <div class="banner"> <img src="<?php echo Yii::app()->request->baseurl;?>/img/story-banner.jpg" class="img-responsive"> </div><!--banner ending here--><br> <div class="story-content"> <div class="row"> <div class="col-md-8 col-md-offset-2 vol-stories"> <div class="media"> <div class="media-left"> <a href="user-profile.php"> <img class="media-object" src="<?php echo Yii::app()->request->baseurl;?>/img/media.jpg"> </a> </div> <div class="media-body"><strong><?php echo $test->user->username;?></strong> <!--username will come here--> <h4 class="media-heading"><strong><br><br><?php echo $model->story_title?></strong></h4><!--title will come here--> <p><?php echo $model->story_text?></p><!--story will come here--> </div> </div><!--Media ending here--> </div> </div><!--row ending here--> </div><!--content ending here--> </div><!--container ending here--> 

если вы хотите всю историю

 public function actionAllstory() //This has been added to view all the stories on the stories page { $allmodels = Story::model()->findAll(); $this->layout='main'; $this->render('allstory', array('allmodels' => $allmodels)); } 

в представлении (упрощенном allstory.php)

 <div class="content"> <div class="banner"> <img src="<?php echo Yii::app()->request->baseurl;?>/img/story-banner.jpg" class="img-responsive"> </div><!--banner ending here--><br> <div class="story-content"> <div class="row"> <div class="col-md-8 col-md-offset-2 vol-stories"> <div class="media"> <div class="media-left"> <a href="user-profile.php"> <img class="media-object" src="<?php echo Yii::app()->request->baseurl;?>/img/media.jpg"> </a> </div> <?php foreach($allmodels as $model){ echo "<h4 class='media-heading'><strong>" . $model->story_title ."</strong></h4>" ; //<!--title will come here--> echo "<p>" . $model->story_text . "</p>" ; // <!--story will come here--> } ?> </div><!--Media ending here--> </div> </div><!--row ending here--> </div><!--content ending here--> </div><!--container ending here-->