I am having trouble with updating the content of two tables. The tables are about users, first table is used for login purposes, so it contains username, email and pass, while the second one is used for user details. Both are connected with the ID of the user row. I am having trouble updating these contents. Here is my code, I am new to CI, so basically don't have a clue what goes wrong.
controller:
<?php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Student extends CI_Controller {
public function index()
{
$this->load->model('student_model');
$data['all_students'] = $this->student_model->get_student_list();
$this->load->view('admin_panel', $data);
}
public function view_student()
{
$this->load->model('student_model');
$data['one_student'] = $this->student_model->get_one_student();
$this->load->view('view_student', $data);
}
public function edit_student()
{
$this->load->model('student_model');
$data['one_student'] = $this->student_model->get_one_student();
$this->load->view('edit_student', $data);
}
public function update_student()
{
$this->load->model('student_model');
$data['update_student'] = $this->student_model->update_student();
$this->load->view('admin_panel', $data);
}
}
View
<?php $this->load->view('worker_templates/wheader');
$this->output->enable_profiler(TRUE);
$this->load->helper('form');
echo "<br/><br/><br/><br/><br/>";
echo form_open('student/update_student');
foreach ($one_student as $key => $value)
{
echo "<div class='col-md-6'>";
echo form_label('Name ', 'worker_name');
echo form_input('Name', $value['worker_name']);
echo form_label('Role ', 'role');
echo form_input('Role', $value['role']);
echo form_label('Email ', 'worker_email');
echo form_input('Email', $value['worker_email']);
echo "<br/><br/>";
echo form_label('Phone ', 'phone');
echo form_input('Phone', $value['phone']);
...
This is very long, So I'm not copying it all to bore you.
Model:
public function get_one_student() //used to show a student, also to display data of one student for update
{
$this->db->select('*');
$this->db->from('workers');
$this->db->join('worker_details', 'worker_details.student_id = workers.worker_id');
$this->db->where('worker_id', $_GET['id']);
$q = $this->db->get();
return $q->result_array();
}
public function update_student()
{
$data = array(
'worker_name' => $this->input->post('worker_name'),
'worker_email' => $this->input->post('worker_email'),
'role' => $this->input->post('role'));
$this->db->update('workers', $data); //first table
$data2 = array(
'phone' => $this->input->post('phone'),
'date_of_birth' => $this->input->post('date_of_birth'),
'sex' => $this->input->post('sex'),
'university' => $this->input->post('university'),
'speciality' => $this->input->post('speciality'),
... //again, very long, not including it all
);
$this->db->update('worker_details', $data2);//second table
}
You need to correct your update_student() function in model. please post worker_id in hidden from your html form and correct function as below.
public function update_student()
{
$data = array(
'worker_name' => $this->input->post('worker_name'),
'worker_email' => $this->input->post('worker_email'),
'role' => $this->input->post('role'));
$this->db->where('worker_id', $this->input->post('worker_id'));
$this->db->update('workers', $data); //first table
$data2 = array(
'phone' => $this->input->post('phone'),
'date_of_birth' => $this->input->post('date_of_birth'),
'sex' => $this->input->post('sex'),
'university' => $this->input->post('university'),
'speciality' => $this->input->post('speciality'),
... //again, very long, not including it all
);
$this->db->where('worker_id', $this->input->post('worker_id'));
$this->db->update('worker_details', $data2);//second table
}
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).
Code-igniter Session is not storing data, it only saves the Email which we are entering in input box in login-form. I set this $config['sess_use_database'] = TRUE; and created a ci_sessions table also in DB but no sake. I tried this on both versions on code-igniters(2 & 3) Please help me to sort out this problem. Thank you. This is my code. First one is controller and the second one is model.
public function validate_credentials()
{
$this->load->model('passenger_login_model');
$query = $this->passenger_login_model->validate();
if($query)
{
$data = array(
'Email' => $this->input->post('Email'),
'is_logged_in' => true,
'P_ID' => $query->P_ID,
'CNIC' => $query->CNIC
);
$this->session->set_userdata($data);
echo $this->session->userdata('Email');
echo $this->session->userdata('P_ID');
//redirect('front');
}
else
{
echo "<script>alert('Incorrect Email or Password!');</script>";
$this->index();
}
}
and as output, it only shows me the user#user.com not P_ID
and this is model
class Passenger_Login_model extends CI_Model
{
/*`passenger`(`P_ID`, `Name`, `Image`, `CNIC`, `Passport_No`, `Gender`, `Email`,
`Password`, `Phone_No`, `Mob_No`, `Address_1`, `Address_2`, `Date` */
function validate()
{
$data=array(
'Email' =>$this->input->post('Email'),
'Password' =>$this->input->post('Password')
);
$rec=$this->db->get_where('passenger', $data)->result();
$c = count($rec);
if($c>0)
{
return true;
}
else
{
return false;
}
}
function is_logged_in()
{
$this->load->library('session');
$is_logged_in = $this->session->userdata('is_logged_in');
if(!isset($is_logged_in) || $is_logged_in != true)
{
echo 'You don\'t have permission to access this page.'.anchor('login',"Login");
die();
}
}}
You should return the data fetch from your model query, use fetch function to do that, for more reference click, So your model validate function should be
function validate()
{
$data=array(
'Email' =>$this->input->post('Email'),
'Password' =>$this->input->post('Password')
);
$rec=$this->db->get_where('passenger', $data);
return $rec->result_array(); // returns data as array // might help you
}
return $res->result_array(); will return multipdimentional array of data from db, to know more about result_array() check this
Session issue is from your controller function the result is array now.
public function validate_credentials()
{
$this->load->model('passenger_login_model');
$result_data = $this->passenger_login_model->validate();
// result data is array now
if(is_array($result_data) && count($result_data) > 0)
{
// var_dump($result_data); // check this var_dump you will get multidimensional array
$data = array(
'Email' => $this->input->post('Email'),
'is_logged_in' => true,
'P_ID' => $result_data[0]['P_ID'],
'CNIC' => $result_data[0]['CNIC']
);
$this->session->set_userdata($data);
echo $this->session->userdata('Email');
echo $this->session->userdata('P_ID');
//redirect('front');
}
else
{
echo "<script>alert('Incorrect Email or Password!');</script>";
$this->index();
}
}
Hope this help, Happy coding.
My problem solved, i just updated the model to this...
function validate()
{
$data=array(
'Email' =>$this->input->post('Email'),
'Password' =>$this->input->post('Password')
);
$query = $this->db->get('passenger');
if ($query->num_rows())
{
return $query->row();
}
}
I have created a Facebook App that i need people to only enter their data to once.
It's all working and the database is being populated, but i need to make sure people don't keep coming back and re-entering their data endlessly.
What's the best way to check if the user has already submitted their data ?
The signed_request could still have been submitted and their data not entered so i need the check for both to work.
Ideally the PHP would just check for FB ID + other data, and only display a confirmation / thankyou page.
Currently my php to send to the database is:
class Users_Model extends CI_Model {
protected $_name = 'users';
function add($id,$key,$value) {
$data = array(
'id' => $id,
'name' => $key,
'value' => $value
);
return $this->db->insert($this->_name, $data);
}
function update($id,$key,$value) {
$data = array(
'value' => $value
);
$this->db->where(array(
'id' => $id,
'name' => $key
));
return $this->db->update($this->_name, $data);
}
function exists($id,$key=null) {
if($key == null) {
$this->db->where(array(
'id' => $id
));
} else {
$this->db->where(array(
'id' => $id,
'name' => $key
));
}
$query = $this->db->get($this->_name);
if($query->num_rows() > 0) {
return true;
}
return false;
}
function remove($id) {
$data = array(
'id' => $id,
);
return $this->db->delete($this->_name, $data);
}
function all() {
$query = $this->db->get($this->_name);
$results = array();
if($query->num_rows() > 0) {
foreach($query->result() as $row) {
$results[]=$row;
}
}
return $results;
}
}
Any help much appreciated...
What's the best way to check if the user has already submitted their data ?
Check if you already have a record for the user’s Facebook id in your database.
I am trying to get a user to enter their details and then store those in a database using codeigniter. When I try and add an entry I get taken to the page where it says success but it does not add anything to the database.
Here are the model and the controller files -
signup.php - This is the controller
<?php
class Signup extends CI_Controller{
function index(){
$this->load->view('signup_form');
}
function insert_member(){
//load model
$this->load->model('insert_member_model');
if($q = $this->insert_member_model->new_member()){
$data['content'] = 'success';
$this->load->view('trial', $data);
}
}
}
insert_member_model.php - This is the model
class Insert_member_model extends CI_Model{
function new_member(){
$new_member_data = array(
'first_name' => $this->input->post('first_name'),
'last_name' => $this->input->post('last_name'),
'username' => 'NULL',
'password' =>$this->input->post('password'),
'email_address' => $this->input->post('email_address')
);
$insert = $this->db->where('membership', $new_member_data);
return $insert;
}
}
Can anyone please help.
Thanks in advance
In insert_member_model.php Replace:
$this->db->where('membership', $new_member_data);
with:
$this->db->insert('membership', $new_member_data);
To insert the data into the database.
Hi I've created a file upload form, it all works perfectly apart from when I press submit it does not re-direct me to the Uploads/add.ctp, but it does save the file to the directory and on to the database.In fact if I point the re-direct to uploads/browse it still does not take me to uploads/browse.
This is my controller
public function add() {
if(!empty($this->data)){
$file = $this->request->data['Upload']['file'];
if ($file['error'] === UPLOAD_ERR_OK && $this->Upload->save($this->data)){
$this->Upload->save($this->data);
if(move_uploaded_file($file['tmp_name'],APP.'webroot/files/uploads'.DS.$this->Upload->id.'.mp4')) {
$this->Session->setFlash(__('<p class="uploadflash">The upload has been saved</p>', true));
$this->redirect(array('controller'=>'Uploads','action' => 'add'));
} else{
$this->Session->setFlash(__('<p class="uploadflash">The upload could not be saved. Please, try again.</p>', true));
}
}
}
}
and this is my form
<div class="maincontent">
<?php echo $this->Form->create('Upload', array('type' => 'file', 'class'=>'uploadfrm'));?>
<fieldset class='registerf'>
<legend class='registerf2'>Upload a Video</legend>
<?php
echo 'Upload your video content here, there is no size limit however it is <b>.mp4</b> file format only.';
echo '<br/>';
echo '<br/>';
echo $this->Form->input('name', array('between'=>'<br />', 'class'=>'input'));
echo $this->Form->input('eventname', array('between'=>'<br />'));
echo $this->Form->input('description', array('between'=>'<br />', 'rows'=> '7', 'cols'=> '60'));
echo $this->Form->hidden('userid', array('id' => 'user_id','value' => $auth['id']));
echo $this->Form->hidden('username', array('id' => 'username', 'value' => $auth['username']));
echo $this->Form->input('file', array('type' => 'file'));
echo "<br/>"
?>
<?php echo $this->Form->end(__('Submit', true));?>
</fieldset>
<?php
class UploadsController extends AppController {
public $name = 'Uploads';
public $helpers = array('Js');
// Users memeber area, is User logged in…
public $components = array(
'Session',
'RequestHandler',
'Auth'=>array(
'loginRedirect'=>array('controller'=>'uploads', 'action'=>'browse'),
'logoutRedirect'=>array('controller'=>'users', 'action'=>'login'),
'authError'=>"Members Area Only, Please Login…",
'authorize'=>array('Controller')
)
);
public function isAuthorized($user) {
// regular user can access the file uploads area
if (isset($user['role']) && $user['role'] === 'regular') {
return true;
}
// Default deny
return false;
}
function index() {
$this->set('users', $this->Upload->find('all'));
}
// Handling File Upload Function and updating uploads database
public function add() {
if(!empty($this->data)){
$file = $this->request->data['Upload']['file'];
if ($file['error'] === UPLOAD_ERR_OK){
$this->Upload->save($this->data);
if(move_uploaded_file($file['tmp_name'],APP.'webroot/files/uploads'.DS.$this->Upload->id.'.mp4'))
{
$this->redirect(array('controller' => 'Uploads', 'action' => 'add'));
$this->Session->setFlash(__('<p class="uploadflash">The upload has been saved</p>', true));
} }else {
$this->Session->setFlash(__('<p class="uploadflash">The upload could not be saved. Please, try again.</p>', true));
}
}
}
function browse () {
// Find all in uploads database and paginates
$this->paginate = array(
'limit' => 5 ,
'order' => array(
'name' => 'asc'
)
);
$data = $this->paginate('Upload');
$this->set(compact('data'));
}
function recentuploads () {
$uploads = $this->Upload->find('all',
array('limit' =>7,
'order' =>
array('Upload.date_uploaded' => 'desc')));
if(isset($this->params['requested'])) {
return $uploads;
}
$this->set('uploads', $uploads);
}
function watch ($id = null){
$this->set('isAjax', $this->RequestHandler->isAjax());
// Read Uploads Table to watch video
$this->Upload->id = $id;
$this->set('uploads', $this->Upload->read());
// Load Posts Model for comments related to video
$this->loadModel('Post');
$this->paginate = array(
'conditions' => array(
'uploadid' => $id),
'limit' => 4
);
$data = $this->paginate('Post');
$this->set(compact('data'));
// Load Likes Model and retrive number of likes and dislikes
$this->loadModel('Like');
$related_likes = $this->Like->find('count', array(
'conditions' => array('uploadid' => $id)
));
$this->set('likes', $related_likes);
}
}
?>
Any suggestions?
This add function is in your UploadsController, correct? And you want it to redirect to uploads/browse?
In your UploadsController, what is $name set to?
<?php
class UploadsController extends AppController {
public $name = ?; // What is this variable set to?
}
By Cake's Inflector, when you specify controllers in a redirect, it should be lowercase:
$this->redirect(array('controller' => 'uploads', 'action' => 'browse'));
Or if the action you direct from and the action you want to direct to are in the same controller, you do not even need to specify the controller. For example if you submit the form from UploadsController add() and you want to redirect to browse():
$this->redirect(array('action' => 'browse'));
Try that and see if it helps.
Also note that you are calling $this->Upload->save($this->data) twice in your add function.
public function add() {
if(!empty($this->data)){
$file = $this->request->data['Upload']['file'];
if ($file['error'] === UPLOAD_ERR_OK && $this->Upload->save($this->data)) {
$this->Upload->save($this->data);
if(move_uploaded_file($file['tmp_name'],APP.'webroot/files/uploads'.DS.$this->Upload->id.'.mp4')) {
$this->Session->setFlash(__('<p class="uploadflash">The upload has been saved</p>', true));
$this->redirect(array('controller'=>'Uploads','action' => 'add'));
} else {
$this->Session->setFlash(__('<p class="uploadflash">The upload could not be saved. Please, try again.</p>', true));
}
}
}
}
Specifically, here:
if ($file['error'] === UPLOAD_ERR_OK && $this->Upload->save($this->data)) {
$this->Upload->save($this->data);
...
When you call it in the if condition, it still saves the data to the database. It is fine to remove the second one.
If I add the following line in the function add
$this->render();
everything works perfectly, I'm struggling for the life of me to work out why I have to render the view if surely all other views are rendered by default.
But anyway got it working!
Hope this helps others :)