Session value saved to database in yii - php

In the form when I echo the session value it is prompted no errors, but when I try to save it on the database in the model the value is not saved.
Here is my view:
(I just posted here what I think is needed.)
<?php
$userid = Yii::app()->session['iduser'];
echo $userid;
?>
Here is my controller:
The contentid, title and content are saved in the database only the userid is my problem. In my database I set the userid as int(11) not null
public function actionContent(){
$model=new ContentForm;
if(isset($_POST['ContentForm'])) {
$model->attributes=$_POST['ContentForm'];
if($model->save())
$this->redirect(array('content','contentid'=>$model->contentid));
$this->redirect(array('content','title'=>$model->title));
$this->redirect(array('content','content'=>$model->content));
$this->redirect(array('content','userid'=>$model->userid));
}
$this->render('content',array('model'=>$model));
}
And here is my model:
<?php
class ContentForm extends CActiveRecord{
public $content;
public $title;
public $userid;
public function tableName(){
return 'tbl_content';
}
public function attributeLabels(){
return array(
'contentid' => 'contentid',
'content' => 'content',
'title' => 'title',
'userid' => 'userid',
);
}
public function rules(){
return array(
array('content, title, userid', 'safe'),
);
}
}

Your user id Stored in Session it can accessed anywhere in the MVC
Try this on your controller
public function actionContent(){
$model=new ContentForm;
if(isset($_POST['ContentForm'])) {
$model->attributes=$_POST['ContentForm'];//The post values
$model->userid=Yii::app()->session['iduser'];
if($model->save())
$this->redirect(array('content','contentid'=>$model->contentid));
//$this->redirect(array('content','title'=>$model->title));
//$this->redirect(array('content','content'=>$model->content)); //Why this to many redirects here the first redirect only works here
//$this->redirect(array('content','userid'=>$model->userid));
}
$this->render('content',array('model'=>$model));
}

Related

YII: Value of variables not saving in the database

I am new to YII. I know this question has been asked a lot of times before nut i can really find an answer. So, please take a look.
I am saving some data in the database from my PaypalController.php
Here is the code of PaypalController.
$transid = $paymentResult['TRANSACTIONID'];
$profileid = $recurringResult['PROFILEID'];
/*var_dump($transid);
var_dump($profileid);
exit;*/
$payment = new Payment;
$payment->user_id = 2;
$payment->feature = 'import sending servers';
$payment->transaction_id = $transid;
$payment->amount = 10;
$payment->profile_id = $profileid;
if($payment->save()){
//var_dump($recurringResult);exit;
//echo "<script>alert('Your payment is succesful');</script>";
$this->redirect('../email-hustler/index');
}else{
print_r($payment->getErrors());
exit;
}
And here is the code of my Payment model
public $user_id;
public $feature;
public $transaction_id;
public $amount;
public $profile_id;
public $is_active;
public function tableName()
{
return '{{payment}}';
}
public function rules()
{
$rules = array(
array('user_id, feature, transaction_id, amount, profile_id, is_active', 'safe'),
);
return CMap::mergeArray($rules, parent::rules());
}
public function attributeLabels(){
return array(
'user_id' => 'user_id',
'feature' => 'feature',
'transaction_id' => 'transaction_id',
'amount' => 'amount',
'profile_id' => 'profile_id',
'is_active' => 'is_active',
);
}
public static function model($className=__CLASS__)
{
return parent::model($className);
}
Now the problem is the value of the variables is not saving but the value i am passing static are saved.
var_dump of variables is giving me correct output.
Please help.

Column not found in SQL laravel 5.4

I'm trying to publish post with user that register in my app, but this error happened:
And I'm using XAMPP and my posts table is this picture
And this error is in phpMyAdmin:
My PostController is:
use App\Post;
class PostsController extends Controller
{
public function __construct()
{
$this->middleware('auth')->except(['index','show']);
}
public function index()
{
$posts=Post::latest()->get();
return view('posts.index',compact('posts'));
}
public function show(Post $post)
{
return view('posts.show',compact('post'));
}
public function create()
{
return view('posts.create');
}
public function store()
{
$this->validate(request(),[
'title'=>'required',
'body' => 'required|min:5'
]);
Post::create(request([
'title' => request('title'),
'body' => request('body'),
'user_id' =>auth()->id()
//auth()->user()->id*/
]));
return redirect()->home;
}
}
and Post Model:
class Post extends Model
{
public function comments()
{
return $this->hasMany(Comment::class);
}
public function user()
{
return $this->belongsTo(User::class);
}
}
It seems your store method is wrong.
Try something like this:
public function store()
{
$this->validate(request(),[
'title'=>'required',
'body' => 'required|min:5'
]);
Post::create([
'title' => request('title'),
'body' => request('body'),
'user_id' =>auth()->id()
]);
return redirect()->home;
}
This code works for you?
INSERT into posts (title, body, userId) VALUES ('My title', 'My body', 7)
The first part specifies the field name, the second part specifies the values you are inserting into each field. 'My title' isn't the field you are inserting info into, it's shown as title.
Also, createdon uses timestamp so you don't need to include that. Updated on could insert a current timestamp once a record is changed.
<?php
if (isset($_POST['submit']))
{
include('../dbcon.php');
$rolno= $_POST['rollno'];
$name= $_POST['name'];
$city= $_POST['city'];
$pcon= $_POST['pcon'];
$std= $_POST['std'];
$imagename= $_FILES['simg'] ['name'];
$tempname= $_FILES['simg'] ['tmp_name'];
move_uploaded_file($tempname,"../dataimg/$imagename");
$qry= "SELECT * FROM `student` WHERE `rollno`='$rolno' AND `name`='$name'";
//$qry="INSERT INTO `student`(`rollno`, `name`, `city`, `pcont`, `standerd`,`image`) VALUES ('$rolno','$name','$city','$pcon','$std','$imagename')";
echo "$qry";
$run= mysqli_query($con,$qry);
if ($run == true)
{
?>
<script>
alert('Data Inserted Successfully.');
</script>
<?php
}
}
?>

Codeigniter - Add data to the database

Im trying add data to the database useing CodeIgniter framework. DB method return true, but I have no new data in database.
There is my controller:
class Facebook extends CI_Controller
{
public function index()
{
if($this->input->is_ajax_request())
{
$this->load->model('user_model','user');
$data = array();
$data['u_ip'] = $this->input->ip_address();
$this->user->add_user($data);
}
}
}
And there is my model:
class User_model extends CI_Model
{
public function add_user($data)
{
$this->db->insert('users',$data);
//$res = $this->db->insert('users',$data); (true)
}
}
Update:
There is my database:
id_users (int 255) AI, key
u_ip (varchar 100)
Also, make sure your $data looks like this:
$data = array(
"u_ip" => $this->input->ip_address(),
);
$this->insert("data", $data);
Or if coming from another file, do this:
$this->insert("users", $data[0];)
Remember to load the dataabse:
$this->load->database();
This will go within add_user($data) eg.
class User_model extends CI_Model
{
public function add_user($data)
{
$this->load->database();
$this->db->insert('users',$data);
//$res = $this->db->insert('users',$data); (true)
}
}
However, you can have these automatically, if you go to autoload.php, you can do this:
$autoload['libraries'] = array('database');
And for your model:
$autoload['model'] = array('logic');
You are not mentioning any column names in your query. Try the below code -
class User_model extends CI_Model{
public $db;
public function __construct(){
parent::__construct();
$this->db = $this->load->database('default',true);
}
public function add($data)
{
$data = array(
'title' => 'My title' ,
'name' => 'My Name' ,
'date' => 'My date'
);
$this->db->insert('mytable', $data);
}
$this->input->is_ajax_request()
is this posted via a form ? if so it should be $this->input->post('is_ajax_request');
is_ajax_request being the name of the input your posting,
If its another function within the controller you need to do $this->is_ajax_request();

How to create Yii form field which shouln't appear in Database

I'm using Yii MongoDbSuite.
I need to create form field for password repeat validation, which shouldn't appear in MongoDB.
Because of I'm using yii forms, all fields which i want to add in view i should declare as public in my model. But my model extend MongoDocument, so all decleared public fields after save() appear in MongoDb. How can i declare field, wich would appear in model, but doesn't appear in Mongo.
In a CActiveRecord model, you can add a property that is not a database column. And it will be treated almost the same as other database backed properties.
public $new_password;
public $new_password_confirm;
...
return array(
array('E_NAME, E_EMAIL, new_password, new_password_confirm', 'required'),
array('new_password', 'compare', 'compareAttribute'=>'new_password_confirm'),
...
<div class="row">
<?php echo $form->labelEx($model, 'new_password'); ?>
<?php echo $form->passwordField($model, 'new_password'); ?>
<?php echo $form->error($model,'new_password'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model, 'new_password_confirm'); ?>
<?php echo $form->passwordField($model, 'new_password_confirm'); ?>
<?php echo $form->error($model,'new_password_confirm'); ?>
</div>
Also a CFormModel model is a model that has no database backed properties.
Unfortunately, due to the way YiiMongoDBSuite works, Nikos' answer won't work completely.
YiiMongoDBSuite saves in a weird way to accomodate the schemaless design of MongoDB by reflecting all public attributes into database attributes.
It starts (in the update function) calling toArray: https://github.com/canni/YiiMongoDbSuite/blob/master/EMongoDocument.php#L593 and then finishs in _toArrray with setting all public attributes as databse properties: https://github.com/canni/YiiMongoDbSuite/blob/master/EMongoEmbeddedDocument.php#L304.
What you can do is set some protected attributes in your model. This should make them not go to the database and be saved, i.e.
class MyAwesomeModel{
public $somedbvar;
protected $somenotdbvar;
}
You can then use that protected property the same way that Nikos' shows.
To improve on #Sammaye 's answer, it is correct, YMDS does assign attributes from class variables.
Although this is not the problem here. The problem here imo, is lazy coding.
Example on how I would tackle the problem
User Model (based on the suit's example)
class User extends EMongoDocument
{
public $username;
public $email;
public $password;
public function getCollectionName()
{
return 'users';
}
public function rules() {
return array(
array('username, email, password', 'required'),
);
}
public function attributeLabels()
{
return array(
'username' => 'UserName',
'email' => 'Email',
'password' => 'Password',
);
}
public static function model($className = __CLASS__)
{
return parent::model($className);
}
public function getForm()
{
$form = new UserForm();
$form->userid = $this->primaryKey();
return $form;
}
}
Form Model :
<?php
class UserForm extends CFormModel
{
public $userid; //something to refer back to your User model on save, you might need this as a hidden field
public $username;
public $email;
public $password;
public $password_again;
public function rules()
{
return array(
array('username, email, password, password_again', 'required'),
array('password', 'compare', 'compareAttribute'=>'password_again', 'strict'=>true),
);
}
public function attributeLabels()
{
return array(
'password_again'=>'Re-type Password',
);
}
public function save()
{
if($this->validate())
{
$user = User::findByPk($this->userid);
$user->username = $this->username;
$user->email = $this->email;
$user->password = hash('sha512',$this->password);
if($user->save())
{
//do stuff
}
}
}
}
And in the view:
<?php
$model = $model->form;
$form = $this->beginWidget('CActiveForm', array(
'id'=>'user-form',
'enableAjaxValidation'=>true,
'enableClientValidation'=>true,
'focus'=>array($model,'firstName'),
));
Ofcourse this is just an example on how to solve your problem without running into problem after problem
(a lazy way that would work btw, is simply declaring an attribute unsafe and never it would never be saved)

Yii - how to retrieve model data into a layout page?

I wish to list some Categories name on my layout main.php page.
Since the layout doesn't have any associated controller or model, I wish to create a static method like this on Category model:
public static function getHeaderModels()
{
// get all models here
return $models;
}
and then in the main layout
<?php
$models = Category::getHeaderModels();
foreach($models as $model)
{
// ....
}
?>
My question is a very basic one:
How can I retrieve those category names from the model ?
Here is the full model:
class Category extends CActiveRecord {
public static function model($className=__CLASS__) {
return parent::model($className);
}
public function tableName() {
return 'category';
}
public function rules() {
return array(
array('parent_id', 'numerical', 'integerOnly' => true),
array('name', 'length', 'max' => 255),
array('id, parent_id, name', 'safe', 'on' => 'search'),
);
}
public function relations() {
return array(
'users' => array(self::MANY_MANY, 'User', 'categories(category_id, user_id)'),
);
}
public function scopes()
{
return array(
'toplevel'=>array(
'condition' => 'parent_id IS NULL'
),
);
}
public function attributeLabels() {
$id = Yii::t('trans', 'ID');
$parentId = Yii::t('trans', 'Parent');
$name = Yii::t('trans', 'Name');
return array(
'id' => $id,
'parent_id' => $parentId,
'name' => $name,
);
}
public function search() {
$criteria = new CDbCriteria;
$criteria->compare('id', $this->id);
$criteria->compare('parent_id', $this->parent_id);
$criteria->compare('name', $this->name, true);
return new CActiveDataProvider(get_class($this), array(
'criteria' => $criteria,
));
}
public static function getHeaderModels() {
//what sintax should I use to retrieve the models here ?
    return $models;
}
May be this answer can help you. First you must create a Widget so you can use it more effectively.
First Create a new widget. Let say the name is CategoryWidget. Put this widget under components directory protected/components.
class CategoryWidget extends CWidget {
public function run() {
$models = Category::model()->findAll();
$this->render('category', array(
'models'=>$models
));
}
}
Then create a view for this widget. The file name is category.php.
Put it under protected/components/views
category.php
<?php if($models != null): ?>
<ul>
<?php foreach($models as $model): ?>
<li><?php echo $model->name; ?></li>
<?php endforeach; ?>
</ul>
<?php endif; ?>
Then call this widget from your main layout.
main.php
// your code ...
<?php $this->widget('CategoryWidget') ?>
...
If I'm not mistaken, you can also pass any variable available in a view, on to the layout.
You just do it from the view that has your variable.
This is the catch: you need to declare the variable which will receive your value, in the controller, like this:
<?php
class MyController extends Controller
{
public $myvariable;
After this, you will assign your model or whatever to this public variable inside your view,
like this:
$this->myvariable = $modeldata;
After you have assigned your model data to controller's public attribute,
you can easily display it inside your layout e.g.
echo $this->myvariable;
Yii already does this by assigning menu items to column2 sidebar menu, from view, like this:
$this->menu=array(
array('label'=>'List Item', 'url'=>array('index')),
array('label'=>'Manage Item', 'url'=>array('admin')),
);
You can see it in all create/update views that gii crud creates.

Categories