UPDATE2:
I've created a new WebUser.php component in /protected/components as follows:
<?php
class WebUser extends CWebUser{
private $_model;
function getId(){
$user = $this->loadUser(Yii::app()->user->id);
return $user->id;
}
protected function loadUser($id=null){
if($this->_model===null)
{
if($id!==null)
{
$this->_model=Users::model()->findByPk($id);
}
return $this->_model;
}
}
}
I've registered the component in main.php as well. After uploading changes, my app still states that WebUser.getId is not defined.
UPDATE:
After making changes and then rolling them back, I'm getting a new error:
Property "CWebUser.getId" is not defined.
The snippet of code in question is:
$user = Users::model()->find('username=?', array(
Yii::app()->user->getId));
How and where should getId be set to reference the $id field in the Users model?
My UserController is throwing the following SQL Error:
CDbCommand failed to execute the SQL statement: SQLSTATE[HY093]: Invalid parameter number:
parameter was not defined. The SQL statement executed was: SELECT * FROM `users` `t` WHERE
username=? LIMIT 1
The error is being caused by this snippet of the controller:
public function actionProfile($id=''){
$user = Users::model()->find('username=?', array(Yii::app()->user->getId()));
if(!$id){
$id = $user->id;
if(!$id)
$this->redirect('login');
}
if( getUserSess('user_type') == 'Sitter') {
$this->render('profile_detail', array('user_id' => $id ));
} else {
$this->render('petowner_profile_detail',array(
'model'=>$this->loadModel($id),
));
}
}
The profile_detail view is as follows:
<?php
if(!$user_id){
$user_id = getUserSess('id');
}
$this->widget('ext.UserProfile.BasicProfile',array('user_id'=>$user_id)); ?>
<?php //$this->widget('ext.UserProfile.UserServices',array('user_id'=>$user_id)); ?>
The petowner_profile_detail view is as follows:
<?php $this->widget('zii.widgets.CDetailView', array(
'data'=>$model,
'attributes'=>array(
'username',
'email',
'phone',
'fname',
'lname',
'address1',
'address2',
'city',
'state',
'zip',
'is_year_old',
'user_type',
// 'register_date',
// 'varified_date',
// 'is_premium',
// 'last_login',
),
)); ?>
How do I rectify he SQL error?
UPDATE:
$user = Users::model()->find('username=:id', array(":id" => Yii::app()->user->id));
UPDATE2:
Yii::app()->user->getId() or Yii::app()->user->id not Yii::app()->user->getId
Related
Sorry for my bad english but i have a problem when i try to open localhost:8080/blog this message show up
Too few arguments to function App\Controllers\Blog::view(), 0 passed in C:\xampp\htdocs\baru\vendor\codeigniter4\framework\system\CodeIgniter.php on line 896 and exactly 1 expected
so this is the controller:
use CodeIgniter\Controller;
use App\Models\ModelsBlog;
class Blog extends BaseController
{
public function index()
{$data = [
'title' => 'artikel'
];
$model = new ModelsBlog();
if (!$this->validate([]))
{
$data['validation'] = $this->validator;
$data['artikel'] = $model->getArtikel();
return view('view_list',$data);
}
}
public function form(){
$data = [
'title' => 'Edit Form'
];
helper('form');
return view('view_form', $data);
}
public function view($id){
$data = [
'title' => 'artikel'
];
$model = new ModelsBlog();
$data['artikel'] = $model->PilihBlog($id)->getRow();
return view('view',$data);
}
public function simpan(){
$model = new ModelsBlog();
if ($this->request->getMethod() !== 'post') {
return redirect()->to('blog');
}
$validation = $this->validate([
'file_upload' => 'uploaded[file_upload]|mime_in[file_upload,image/jpg,image/jpeg,image/gif,image/png]|max_size[file_upload,4096]'
]);
if ($validation == FALSE) {
$data = array(
'judul' => $this->request->getPost('judul'),
'isi' => $this->request->getPost('isi')
);
} else {
$upload = $this->request->getFile('file_upload');
$upload->move(WRITEPATH . '../public/assets/blog/images/');
$data = array(
'judul' => $this->request->getPost('judul'),
'isi' => $this->request->getPost('isi'),
'gambar' => $upload->getName()
);
}
$model->SimpanBlog($data);
return redirect()->to('./blog')->with('berhasil', 'Data Berhasil di Simpan');
}
public function form_edit($id){
$data = [
'title' => 'edit artikel'
];
$model = new ModelsBlog();
helper('form');
$data['artikel'] = $model->PilihBlog($id)->getRow();
return view('form_edit',$data);
}
public function edit(){
$model = new ModelsBlog();
if ($this->request->getMethod() !== 'post') {
return redirect()->to('blog');
}
$id = $this->request->getPost('id');
$validation = $this->validate([
'file_upload' => 'uploaded[file_upload]|mime_in[file_upload,image/jpg,image/jpeg,image/gif,image/png]|max_size[file_upload,4096]'
]);
if ($validation == FALSE) {
$data = array(
'judul' => $this->request->getPost('judul'),
'isi' => $this->request->getPost('isi')
);
} else {
$dt = $model->PilihBlog($id)->getRow();
$gambar = $dt->gambar;
$path = '../public/assets/blog/images/';
#unlink($path.$gambar);
$upload = $this->request->getFile('file_upload');
$upload->move(WRITEPATH . '../public/assets/blog/images/');
$data = array(
'judul' => $this->request->getPost('judul'),
'isi' => $this->request->getPost('isi'),
'gambar' => $upload->getName()
);
}
$model->edit_data($id,$data);
return redirect()->to('./blog')->with('berhasil', 'Data Berhasil di Ubah');
}
public function hapus($id){
$model = new ModelsBlog();
$dt = $model->PilihBlog($id)->getRow();
$model->HapusBlog($id);
$gambar = $dt->gambar;
$path = '../public/assets/blog/images/';
#unlink($path.$gambar);
return redirect()->to('./blog')->with('berhasil', 'Data Berhasil di Hapus');
}
}
ModelsBlog.php :
use CodeIgniter\Model;
class ModelsBlog extends Model
{
protected $table = 'artikel';
public function getArtikel()
{
return $this->findAll();
}
public function SimpanBlog($data)
{
$query = $this->db->table($this->table)->insert($data);
return $query;
}
public function PilihBlog($id)
{
$query = $this->getWhere(['id' => $id]);
return $query;
}
public function edit_data($id,$data)
{
$query = $this->db->table($this->table)->update($data, array('id' => $id));
return $query;
}
public function HapusBlog($id)
{
$query = $this->db->table($this->table)->delete(array('id' => $id));
return $query;
}
}
And this is the view.php:
<body style="width: 70%; margin: 0 auto; padding-top: 30px;">
<div class="row">
<div class="col-lg-12 margin-tb">
<div class="pull-left">
<h2><?php echo $artikel->judul; ?></h2>
</div>
</div>
</div>
<hr>
<div class="row">
<div class="col-lg-12">
<div class="row">
<?php
if (!empty($artikel->gambar)) {
echo '<img src="'.base_url("assets/blog/images/$artikel->gambar").'" width="30%">';
}
?>
<?php echo $artikel->isi; ?>
</div>
</div>
</div>
</body>
i cant find any solutions for this error, pls help thank you very much
Let's go over what you're telling the code to do.
First, you make a call to /blog. If you have auto-routing turned on this will put you forward to the controller named 'Blog'.
class Blog extends BaseController
And since you do not extend the URL with anything, the 'index' method will be called.
public function index()
{$data = [
'title' => 'artikel'
];
$model = new ModelsBlog();
if (!$this->validate([]))
{
$data['validation'] = $this->validator;
$data['artikel'] = $model->getArtikel();
return view('view_list',$data);
}
}
The index method sets $data to an array filled with 'title' => 'artikel'. And then fills $model with a new ModelsBlog.
class ModelsBlog extends Model
There is no __construct method defined in ModelsBlog so just the class is loaded and specific execution related to $model stops there, which is fine.
Then, the index() from Blog goes on and checks whether or not $this->validate([]) returns false. Since there's no else statement, if $this->validate([]) were to return true, code execution would stop there. So we'll assume $this->validate([]) returns false. So far so good, there's nothing weird going on with your code.
However, IF $this->validate([]) returns false, you tell the index() to return the function called view(). Normally CodeIgniter would serve you the view you set as the first parameter. But since you also have a Blog method named 'view', CodeIgniter will try to reroute te request to that method. So in other words, the actual request you're trying to make is:
Blog::view()
And since you've stated that view() receives 1 mandatory parameter, the requests triggers an error. You can solve the problem by either renaming the view() method of Blog to something like 'show()' or 'read()'. Anything else that does not conflict with the native CodeIgniter view() function would be good.
Honestly though, you are sending through two parameters in the index() function call so I'm slightly confused why the error generated states you provided 0, but I hope at least you gain some insight from my answer and you manage to fix the problem.
If anyone could provide more information regarding this, feel free to comment underneath and I'll add your information to the answer (if it gets accepted).
How to check for author with Doctrine Query?
class UserController extends Controller
{ ...
/**
* #Route("/join/{id}", name="join_event")
*/
public function joinAct(Request $request, $id)
{
What Query for check? Condition: IF $id (field 'content_id') AND UserID (field 'user_id') exist in table, THEN message: 'You are an author!', ELSE do some code.
$authorcheck = $this->getDoctrine()
->getRepository('MyBundle:User')
->find($id AND $this->getUser()->getId());
End Query
if ($authorcheck) {
$message = ['text' => 'You are an author!', 'type' => 'success'];
}
else {
DoSomeCode...
}
}
}
Any ideas?
$authorcheck = $this
->getDoctrine()
->getRepository('MyBundle:User')
->findBy(array(
'id' => $id,
'user' => $this->getUser()
));
Should be fine for what you need.
Disclaimer
As I don't know fields name and so on, you'll probably need to arrange this in order to work
I'm getting an error on form validation as well as db error. When I remove form validation the db query works perfectly fine. I have no idea what the error is and how to solve it.
A PHP Error was encountered
Severity: Notice
Message: Undefined offset: 1
Filename: libraries/Form_validation.php
Line Number: 953
A Database Error Occurred
Error Number: 1064
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'WHERE ` = 'admin' LIMIT 1' at line 2
SELECT * WHERE ` = 'admin' LIMIT 1
Filename: C:\wamp\www\myblog.com\system\database\DB_driver.php
Line Number: 330
[Controller: myblog]
class Myblog extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->model('blogmodel');
}
public function login()
{
$this->load->view('header');
$this->load->view('login');
$this->load->view('footer');
}
public function login_check()
{
$user=$this->input->post("username");
$pass=$this->input->post("password");
$this->form_validation->set_rules('username', 'Username', 'trim|required|is_unique');
$this->form_validation->set_rules('password', 'Password', 'trim|required|min_length[4]|max_length[32]');
if($this->form_validation->run()==true)
{
$this->blogmodel->checklogin($user,$pass);
$this->load->view('header');
$this->load->view('logsuccess');
$this->load->view('footer');
}
else
{
$this->load->view('header');
$this->load->view('login');
$this->load->view('footer');
}
}
public function reg()
{
$this->form_validation->set_rules('username', 'Username', 'trim|required|is_unique');
$this->form_validation->set_rules('password', 'Password', 'trim|required|min_length[4]|max_length[32]');
if($this->form_validation->run()==true)
{
$user=$this->input->post("username");
$pass=$this->input->post("password");
$this->blogmodel->register($user,$pass);
$this->load->view('header');
$this->load->view('regsuccess');
$this->load->view('footer');
}
else
{
redirect('myblog/login');
}
}
[Model: blogmodel]
class Blogmodel extends CI_Model {
function __construct() {
parent::__construct();
}
function checklogin($user,$pass)
{
$this->db->select('username, password');
$this->db->from('user');
$this->db->where('username', $user);
$this->db->where('password', MD5($pass));
$this->db->limit(1);
$query = $this->db->get();
if($query->num_rows() == 1) {
return $query->result();
} else {
redirect('myblog/login');
}
}
function register($user,$pass)
{
$new_member=array(
'username' => $user,
'password' => md5($pass),
'status' =>1
);
$insert = $this->db->insert('user', $new_member);
return $insert;
}
[View:login]
echo "<h2>Register</h2>";
echo validation_errors();
echo form_open('myblog/reg');
echo form_label("Username: ");
echo form_input("username");
?><br/>
<?php
echo form_label("Password: ");
echo form_password("password");
?><br/>
<?php
echo form_label("Confirm Password: ");
echo form_password("password2");
?><br/>
<?php
echo form_submit("","Register");
echo form_close();
echo "<h2>Login</h2>";
echo validation_errors();
echo form_open('myblog/login_check');
echo form_label("Username: ");
echo form_input("username");
?><br/>
<?php
echo form_label("Password: ");
echo form_password("password");
?><br/>
<?php
echo form_submit("","Login");
echo form_close();
My guess is because you haven't set a table or row in your form validation.
Change this line, in your Controller;
$this->form_validation->set_rules('username', 'Username', 'trim|required|is_unique');
to this;
$this->form_validation->set_rules('username', 'Username', 'trim|required|is_unique[users.username]');
As you'll see, I've added [users.username] to the is_inque rule. Without it, CI doesn't know what to compare it to.
The SQL Statement is missing the table and column to check
SELECT * FROM table WHERE column = 'admin' LIMIT 1
SQL syntax incorrect.
Your incomplete sql statement indicates that you want to fetch a COLUMN VALUE from a TABLE that contains the values of your Username.
So.include an appropriate Column name and table name,
Syntax:
Select * from table_name where column_name='admin' Limit 1;
I am new in YII framework. I am doing update operation using YII framework. I have controller with name sitecontroller.php, model jobseekerprofile.php, view personal.php.
I got the error:
Fatal error: Call to a member function isAttributeRequired() on a non-object in E:\wamp\www\yii\framework\web\helpers\CHtml.php on line 1414
My table is job_seeker_profile
Fields
1.id
2.user_id
3.contact_no
4.gender
5.dob
6.mstatus
7.address
8.location_id
I want to edit the data in contact_no and address according to user_id
Model-Jobseekerprofile.php - rules
public function rules()
{
return array(
array('contact_no,address','required'),
);
}
controller-Sitecontroller.php
class SiteController extends Controller {
public function actionpersonal()
{
$user_id = trim($_GET['id']);
$model=Jobseekerprofile::model()->find(array(
'select'=>'contact_no,address',"condition"=>"user_id=$user_id",
'limit'=>1,));
$model = Jobseekerprofile::model()->findByPk($user_id);
if(isset($_POST['Jobseekerprofile']))
{
$model->attributes=$_POST['Jobseekerprofile'];
if($model->save())
{
$this->redirect(array('profile','user_id'=>$model->user_id));
}
}
$this->render('personal',array('model' =>$model));
}
}
Anybody help me?
Seems that $model = Jobseekerprofile::model()->findByPk($user_id) is not finding anything, so $model is null, and that is why $model->isAttributeRequired() throws an error. Check your incoming params because of this and check if there a profile with such id (or maybe you should search by attributes instead of by id?).
Besides you can use
public function actionPersonal($id) {
$model = Jobseekerprofile::model()->findByPk($id);
//
}
Instead of
public function actionpersonal() {
$user_id = trim($_GET['id']);
$model = Jobseekerprofile::model()->findByPk($user_id);
//
}
public function actionpersonal() {
$user_id = trim($_GET['id']);
$model = Jobseekerprofile::model()->findByPk($user_id);
if (isset($_POST['Jobseekerprofile'])) {
$model->attributes = $_POST['Jobseekerprofile']; //post key edited
if ($model->save()) {
$this->redirect(array('profile', 'user_id' => $model->user_id));
}
}
$this->render('personal', array('model' => $model));
}
First Check what you are getting in $_POST
and if all is ok then try to save like
$model = Jobseekerprofile::model()->findByPk($user_id);
if (isset($_POST['Jobseekerprofile'])) {
$model->attributes = $_POST['jobseekerprofile'];
$model->contact_no= $_POST['Jobseekerprofile']['contact_no']; //post key edited
$model->address = $_POST['Jobseekerprofile']['address'];
if ($model->save()) {
$this->redirect(array('profile', 'user_id' => $model->user_id));
}
}
$this->render('personal', array('model' => $model));
if not work then check what model returns
$error=$model->getErrors();
print_r($error);
above code surely gives you idea why it is not saving
Hello everybody i need help on codeigniter roles or permision. i have one user role (the admin) :
Table users ine the database :
id int(11)
email varchar(100)
password varchar(128)
name varchar(100)
in my admin panel i have (page.php controller)=page management, page order, (agent.php controller) = add,edit,delete... , (gyms) = add,edit,delete... ,(article.php controller)
and i have 21 sections, for each section i have more than one treatment, what i want is to assign to each section an admin than can edit and view only his section. so i will have 21 section_admin and one (or more) global_admin than can manage everything
i add an other field in users table named type :
type varchar(50)
it will have two values section_admin or global_admin. I searched but i found no tutorial that shows me how do that.
i don't know how to integrate roles management in my system. Can someone help me?
The controler : user.php
class User extends Admin_Controller
{
public function __construct ()
{
parent::__construct();
}
public function index ()
{
// Fetch all users
$this->data['users'] = $this->user_m->get();
// Load view
$this->data['subview'] = 'admin/user/index';
$this->load->view('admin/_layout_main', $this->data);
}
public function edit ($id = NULL)
{
// Fetch a user or set a new one
if ($id) {
$this->data['user'] = $this->user_m->get($id);
count($this->data['user']) || $this->data['errors'][] = 'User could not be found';
}
else {
$this->data['user'] = $this->user_m->get_new();
}
// Set up the form
$rules = $this->user_m->rules_admin;
$id || $rules['password']['rules'] .= '|required';
$this->form_validation->set_rules($rules);
// Process the form
if ($this->form_validation->run() == TRUE) {
$data = $this->user_m->array_from_post(array('name', 'email', 'password'));
$data['password'] = $this->user_m->hash($data['password']);
$this->user_m->save($data, $id);
redirect('admin/user');
}
// Load the view
$this->data['subview'] = 'admin/user/edit';
$this->load->view('admin/_layout_main', $this->data);
}
public function delete ($id)
{
$this->user_m->delete($id);
redirect('admin/user');
}
public function login ()
{
// Redirect a user if he's already logged in
$dashboard = 'admin/dashboard';
$this->user_m->loggedin() == FALSE || redirect($dashboard);
// Set form
$rules = $this->user_m->rules;
$this->form_validation->set_rules($rules);
// Process form
if ($this->form_validation->run() == TRUE) {
// We can login and redirect
if ($this->user_m->login() == TRUE) {
redirect($dashboard);
}
else {
$this->session->set_flashdata('error', 'That email/password combination does not exist');
redirect('admin/user/login', 'refresh');
}
}
// Load view
$this->data['subview'] = 'admin/user/login';
$this->load->view('admin/_layout_modal', $this->data);
}
public function logout ()
{
$this->user_m->logout();
redirect('admin/user/login');
}
public function _unique_email ($str)
{
// Do NOT validate if email already exists
// UNLESS it's the email for the current user
$id = $this->uri->segment(4);
$this->db->where('email', $this->input->post('email'));
!$id || $this->db->where('id !=', $id);
$user = $this->user_m->get();
if (count($user)) {
$this->form_validation->set_message('_unique_email', '%s should be unique');
return FALSE;
}
return TRUE;
}
}
The model user_m.php :
protected $_table_name = 'users';
protected $_order_by = 'name';
public $rules = array(
'email' => array(
'field' => 'email',
'label' => 'Email',
'rules' => 'trim|required|valid_email|xss_clean'
),
'password' => array(
'field' => 'password',
'label' => 'Password',
'rules' => 'trim|required'
)
);
public $rules_admin = array(
'name' => array(
'field' => 'name',
'label' => 'Name',
'rules' => 'trim|required|xss_clean'
),
'email' => array(
'field' => 'email',
'label' => 'Email',
'rules' => 'trim|required|valid_email|callback__unique_email|xss_clean'
),
'password' => array(
'field' => 'password',
'label' => 'Password',
'rules' => 'trim|matches[password_confirm]'
),
'password_confirm' => array(
'field' => 'password_confirm',
'label' => 'Confirm password',
'rules' => 'trim|matches[password]'
),
);
function __construct ()
{
parent::__construct();
}
public function login ()
{
$user = $this->get_by(array(
'email' => $this->input->post('email'),
'password' => $this->hash($this->input->post('password')),
), TRUE);
if (count($user)) {
// Log in user
$data = array(
'name' => $user->name,
'email' => $user->email,
'id' => $user->id,
'loggedin' => TRUE,
);
$this->session->set_userdata($data);
}
}
public function logout ()
{
$this->session->sess_destroy();
}
public function loggedin ()
{
return (bool) $this->session->userdata('loggedin');
}
public function get_new(){
$user = new stdClass();
$user->name = '';
$user->email = '';
$user->password = '';
return $user;
}
public function hash ($string)
{
return hash('sha512', $string . config_item('encryption_key'));
}
}
There's too many ways how you can incorporate permission system in your project and it all depends what you need. I will give you a basic idea for your case how I would do it IF I understood your question right:
Yes, you can add another field to user table and call it role
To your section table add a user_id field. This is how you connect user with section.
Once user logs in, veryfy if that user is section_user and if yes you need to pull the right section based on that user_id from db.
If not, it means its a global_admin and then display all sections.
I'm not sure if I understood your question right tho.
Let me know.
Save yourself the trouble and use this: Flexi-Auth. You'll have roles and permissions for all the admin types you want for example.
I'm not sure exactly what you're trying to achieve, but I'll explain roughly what I would do:
1) Define a URL scheme
For example if you had a website for car enthusiasts, each brand might be its own section:
somesite.com/section/honda
somesite.com/section/ford
somesite.com/section/toyota
Those URL slugs (honda, ford, toyota etc) effectively become the identifiers for the section you're trying to access. Each one is unique.
You would then want to make sure that each slug after /section/ is a parameter rather than a function call. You can do this by going into /application/config/routes.php and defining a route like this:
$route['section/(:any)'] = section_controller/$1;
// $1 is the placeholder variable for the (:any) regex. So anything that comes after /section will be used as a parameter in the index() function of the section_controller class.
2. Create a new database called 'section', and a corresponding model
For now just give it two fields: *section_id*, and *section_name*. This will store each unique section. The code for the model would be something like this:
class Section extends CI_Model
{
public $section_name;
public $section_id;
public function loadByName($section_name)
{
$query = $this->db->select('section_id', 'section_name')
->from('section')
->where('section_name', $section_name);
$row = $query->row();
$this->section_name = $row->section_name;
$this->section_id = $row->section_id;
return $row;
}
public function loadById($section_id)
{
$query = $this->db->select('section_id', 'section_name')
->from('section')
->where('section_id', $section_id);
$row = $query->row();
$this->section_name = $row->section_name;
$this->section_id = $row->section_id;
return $row;
}
}
3. In the user table, create an additional field called *section_id*
This will be the reference to the ID of the section which they are an admin of. For example if the Toyota section_id is 381, then use 381 as the number in the section_id field in the user table.
4. When the page is requested, look up the section_id based on the slug name.
In your controller file, you should then load the section model somewhere in the index() method like so:
class Section_controller extends CI_Controller
{
public function index($section_name)
{
// I will assume you've already loaded your logged in User somewhere
$this->load->model('Section');
$this->Section->loadByName($section_name);
if ($this->User->section_id == $this->Section->section_id)
{
// Render the page with appropriate permissions
}
else
{
// Throw an error
}
}
}
I won't get into any more specifics of doing all of that; you'll have to read the Codeigniter documentation for a grasp on how to handle routes, controllers, DB queries etc.
if you have only 2 roles then it can achieve easily. you know the user is admin or not if user >is admin then it activate all the section where admin has acess. if user is then he won,t able >to gain access.
if you are comfortalbe to use tankauth authentication library if you have enough time to do task then go to tankauth.
you can also use bonfire(HMVC) for user authentication.