I am trying to connect to a different database. I have a script for creating a new instance from an SQL file. I am creating users by inserting into the main database table and then using the same database as the master login table with all the users. I am trying to login to another database and use that database. I am getting a blank home page on trying to login to another database and also in some cases I am not able to connect to another database at all and end up using the same master db. I am storing the company name in a session and using it in all model files and connecting to the db. I tried everything but nothing seems to work. My controller model and view files are as follows:
model: mod_login.php
<?php
class mod_login extends CI_Model{
var $myTables;
#print_r($this->db->last_query());
function __construct(){
parent::__construct();
$companyName = $companyName = $this->session->userdata('company');
$otherdb = $this->load->database("$companyName", TRUE);
$this->myTables=$this->config->item('myTables');
$this->load->helper('cookie');
}
function validate_admin_login(){
$this->form_validation->set_rules('username', 'Username', 'trim|required');
$this->form_validation->set_rules('userpass', 'Password', 'trim|required');
if ($this->form_validation->run() == TRUE){
return $this->check_admin_login();
}else{
return validation_errors();
}
}
function check_cookie_login(){
$this->db->where('username', trim($this->input->cookie('uusername')));
$this->db->where('userpass ', sha1(trim($this->input->cookie('userpass'))));
$this->db->where('status', '1');
$this->db->where('deleted', '0');
$this->db->select('*');
$query = $this->db->get($this->myTables['users']);
if($query->num_rows() > 0){
$row = $query->row();
$this->db->where('userid', $row->id);
$this->db->select('firstname,lastname,profileimage');
$query1 = $this->db->get($this->myTables['users_details']);
$row1 = $query1->row();
$newdata = array(
'is_admin_logged_in' => true,
'admin_user_name' => $row->username,
'admin_userpass' => $row->userpass,
'admin_id'=>$row->id,
'admin_lastlogin'=>date("d-m-Y H:i:s",$row->lastlogin),
'admin_lastloginip'=>$row->lastloginip,
'lastrefresh'=>time()
);
$this->session->set_userdata($newdata);
$this->update_admin_login_time($this->session->userdata('admin_id'));
$this->admin_init_elements->set_global_user($row->username,$row->userpass);
if($this->input->post('remember'))
{
$cookie = array('name' => 'username','value' => $row->username,'expire' => time()+7600,'secure' => false);
$this->input->set_cookie($cookie);
}
$name = $row1->firstname.' '.$row1->lastname;
$cookie1 = array('name' => 'name','value' => $name,'expire' => time()+7600,'secure' => false);
$this->input->set_cookie($cookie1);
$cookie2 = array('name' => 'image','value' => $row1->profileimage,'expire' => time()+7600,'secure' => false);
$this->input->set_cookie($cookie2);
return 'Login Successful';
}else{
}
}
function check_admin_login(){
$this->db->where('username', trim($this->input->post('username')));
$this->db->where('userpass ', sha1(trim($this->input->post('userpass'))));
$this->db->where('status', '1');
$this->db->where('deleted', '0');
$this->db->select('*');
$query = $this->db->get($this->myTables['users']);
if($query->num_rows() > 0){
$row = $query->row();
$this->db->where('userid', $row->id);
$this->db->select('firstname,lastname,profileimage,company');
//$query1 = $this->db->query("Select * from pr_users_details where userid = '".$row->id."'");
$query1 = $this->db->get($this->myTables['users_details']);
$row1 = $query1->row();
$newdata = array(
'is_admin_logged_in' => true,
'admin_user_name' => $row->username,
'admin_userpass' => $row->userpass,
'admin_id'=>$row->id,
'admin_lastlogin'=>date("d-m-Y H:i:s",$row->lastlogin),
'admin_lastloginip'=>$row->lastloginip,
'lastrefresh'=>time(),
'company'=>$row1->company
);
$company = $row1->company;
$this->session->set_userdata($newdata);
$companyName = $this->session->userdata('company');
$otherdb = $this->load->database("$companyName", TRUE);
echo "<pre>";
print_r($this->session->all_userdata());
echo "</pre>";
$this->update_admin_login_time($this->session->userdata('admin_id'));
$this->admin_init_elements->set_global_user($row->username,$row->userpass);
if($this->input->post('remember'))
{
$cookie = array('name' => 'username','value' => $row->username,'expire' => time()+7600,'secure' => false);
$this->input->set_cookie($cookie);
}
$name = $row1->firstname.' '.$row1->lastname;
$cookie1 = array('name' => 'name','value' => $name,'expire' => time()+7600,'secure' => false);
$this->input->set_cookie($cookie1);
$cookie2 = array('name' => 'image','value' => $row1->profileimage,'expire' => time()+7600,'secure' => false);
$this->input->set_cookie($cookie2);
return 'Login Successful';
}else{
return 'Incorrect Username or Password.';
}
}
Controller: login.php
<?php
class login extends CI_Controller
{
var $data;
function __construct() {
parent::__construct();
$this->load->helper('cookie');
$is_admin_logged_in = $this->admin_init_elements->admin_logged_in_status();
global $USER;
if($is_admin_logged_in == TRUE){
redirect('home');
//;
}
//populate viewfor header / footer elements
$this->admin_init_elements->init_elements('N');
$this->load->model('mod_login');
}
function index(){
//if Admin already logged in, send to Admin home
$this->data['message']='';
$this->data['msg_class'] = '';
$post_array=$this->input->post();
$data['old_images']=$this->mod_common->getBgImages();
if($this->input->cookie('remember') == 'on')
{
//echo $this->input->cookie('username');
$this->data['message']=strip_tags($this->mod_login->check_cookie_login());
if($this->data['message']=='Login Successful'){
$this->data['msg_class'] = 'sukses';
redirect('home');
}else{
$this->data['msg_class'] = 'gagal';
}
}
if($this->input->post('action')=='adminLogin'){
//print_r($this->input->post()); die;
if(isset($post_array['remember'])){
$username_cookie= array(
'name' => 'uusername',
'value' => $post_array['username'],
'expire' => '865000',
'secure' => FALSE
);
$password_cookie= array(
'name' => 'userpass',
'value' => $post_array['userpass'],
'expire' => '865000',
'secure' => FALSE
);
$remember_cookie= array(
'name' => 'remember',
'value' => 'on',
'expire' => '865000',
'secure' => FALSE
);
$this->input->set_cookie($username_cookie);
$this->input->set_cookie($password_cookie);
$this->input->set_cookie($remember_cookie);
//die;
}
else
{
if($this->input->cookie('remember') == 'on')
{
if($this->input->cookie('uusername') != $post_array['username'])
{
delete_cookie("remember");
delete_cookie("uusername");
delete_cookie("userpass");
}
}
}
$this->data['message']=strip_tags($this->mod_login->validate_admin_login());
if($this->data['message']=='Login Successful'){
$this->data['msg_class'] = 'sukses';
redirect('home');
}else{
$this->data['msg_class'] = 'gagal';
}
} /*else if(isset()){
}*/
///////////////////////
$this->data['cookieRemember'] = $this->input->cookie('remember');
$this->data['cookieUsername'] = $this->input->cookie('username');
$this->data['cookiePassword'] = $this->input->cookie('userpass');
//echo $this->data['cookieRemember'];echo $this->data['cookieUsername']; echo $this->data['cookiePassword'];
//////////////////////
$this->data['cookiename'] = $this->input->cookie('name', false);
$this->data['cookieimage'] = $this->input->cookie('image', false);
$sess_msg = $this->session->userdata('session_msg');
$session_msg_class = $this->session->userdata('session_msg_class');
if(isset($sess_msg) && $sess_msg!= ''){
$this->data['message']=$sess_msg;
$this->data['msg_class'] = $session_msg_class!=''?$session_msg_class:'gagal';
}
//render full layout, specific to this function
$this->load->view('login', $this->data);
}
View: home.php
<?php
class home extends CI_Controller
{
var $data;
function __construct() {
parent::__construct();
//populate viewfor header / footer elements
$this->admin_init_elements->init_elements();
#$this->load->model('admin_m');
}
function index(){
$data = array();
//if Admin already logged in, send to Admin home
#$this->data['maincontent'] = $this->load->view('maincontents/gridview',$data,TRUE);
$data['lastlogin_details'] = $this->admin_lastlogin_details();
$this->data['maincontent'] = $this->load->view('maincontents/dashboard',$data,true);
//render full layout, specific to this function
$this->load->view('layout', $this->data);
}
function admin_lastlogin_details(){
$lastlogin_det['lastlogin'] = $this->session->userdata('admin_lastlogin');
$lastlogin_det['lastloginip'] = $this->session->userdata('admin_lastloginip');
return $lastlogin_det;
}
It displays the home.php but it displays a blank page without errors
Related
I have to combine two array into single inside Json encode. my code is,
// Controller
$email = $this->input->get('email');
$pass = $this->input->get('password');
$enc_pass = 0;
$get_pass = $this->select->selectData($email);
if(!empty($get_pass)) {
foreach($get_pass as $password)
$enc_pass = $password['user_password'];
$dec_pass = $this->encrypt->decode($enc_pass);
if($pass == $dec_pass) {
$details = array('tag' => 'login', 'status' => 'true');
echo json_encode(array_merge($get_pass, $details));
}
else {
$details = array('tag' => 'login', 'status' => 'false', 'error_msg' => 'Incorrect Email or Password');
echo json_encode($details);
}
}
else {
$details = array('tag' => 'login', 'status' => 'false', 'error_msg' => 'Incorrect Email or Password');
echo json_encode($details);
}
// Model
public function selectData($email) {
$query = $this->db->query('SELECT * FROM tbl_user WHERE email = "'.$email.'"');
$count = $query->num_rows();
if($count > 0)
return $result = $query->result_array();
else
return 0;
}
Now the output for the above code is,
{"0":{"user_id":"1","user_name":"Jithin Varghese","user_email":"jithinvarghese111#gmail.com","user_phone":"9947732296","user_status":"1"},"tag":"login","status":"true"}
Required output is,
{"user_id":"1","user_name":"Jithin Varghese","user_email":"jithinvarghese111#gmail.com","user_phone":"9947732296","user_status":"1","tag":"login","status":"true"}
How to get the required output. I have tried a lot. How to implement this.
Thankyou.
Fatal Error: call to a member function uploadFile() on a non-object
Getting this error of upload file function on Uploading File to dropbox using PHP API On live Server. Same Code Working fine on localhost and doing it in codeigniter. start of code is**
<?php
if (!defined('BASEPATH')) exit('No direct script access allowed');
error_reporting(1);
require_once(APPPATH . 'libraries/dropbox/vendor/autoload.php');
use \Dropbox as dbx;
class Knowledge extends CI_Controller
{
public $appInfoFile;
public $requestPath; **
public function __construct()
{
parent::__construct();
$this->load->library('session');
$this->load->helper('form');
$this->load->helper('url');
$this->load->database();
$this->load->library('form_validation');
//load the models
$this->load->model('knowledge_model');
//$this->load->helper('messages');
//$this->load->model('messages_model');
$this->load->model('messages_model', 'send_messages');
// custom library in codeigniter
$this->appInfoFile = APPPATH.'libraries/dropbox/app-info.json';
$redirect_uri ='https://www.domainname.com/knowledge/add/';
$requestPath = $this->init();
session_start();
validate_user();
}
public function index($msg = NULL)
{
$session_data = $this->session->all_userdata();
$data['msg'] = $msg;
if (isset($session_data["validated"]) && $session_data["validated"] == '1') {
$data['title'] = 'Knowledge Center';
$data['records'] = $this->knowledge_model->get_all_rec();
// echo "<pre>".print_r($data['records'],true)."</pre>";exit;
$this->load->view('includes/header', $data);
$this->load->view('includes/sidebar', $data);
$this->load->view('knowledge', $data);
$this->load->view('includes/footer');
} else {
redirect(base_url());
}
}
public function tag($msg = NULL)
{
$tagname = $this->uri->segment("3");
$tagnamehits = $this->uri->segment("4");
$session_data = $this->session->all_userdata();
$data['msg'] = $msg;
if (isset($session_data["validated"]) && $session_data["validated"] == '1') {
$data['title'] = 'Knowledge Center';
$data['update_rec'] = $this->knowledge_model->update_hits($tagnamehits);
$data['records'] = $this->knowledge_model->get_notifyrec_bytags($tagname);
//echo "<pre>".print_r($data['records'],true)."</pre>";exit;
$this->load->view('includes/header', $data);
$this->load->view('includes/sidebar', $data);
$this->load->view('knowledge', $data);
$this->load->view('includes/footer');
} else {
redirect(base_url());
}
}
public function add()
{
//validate form input
$this->form_validation->set_rules('subject', 'subject', 'required');
$this->data['message'] = (validation_errors() ? validation_errors() : $this->session->flashdata('message'));
$seralizedtags = serialize($this->input->post('tagsar'));
//echo "<pre>".print_r($seralizedArray,true)."</pre>";exit;
// drop box upload filess
if (isset($_FILES['attached_file']['name']) && !empty($_FILES['attached_file']['name'])) {
$file_name= $_FILES['attached_file']['name'];
$return_result=$this->upload_to_dropbox($file_name);
$rev=$return_result['rev'];
$mime_type=$return_result['mime_type'];
$path=$return_result['path'];
$size=$return_result['size'];
$revision=$return_result['revision'];
}
if ($this->form_validation->run() == true) {
$session_data = $this->session->all_userdata();
$user_id = $session_data["userid"];
$data = array(
'user_id' => $user_id,
'edit_by_userid' => $user_id,
'subject' => $this->input->post('subject'),
'tags' => $seralizedtags,
'description' => $this->input->post('description'),
'dropbox_rev'=>$rev,
'dropbox_mim_type'=>$mime_type,
'dropbox_path'=>$path,
'dropbox_filesize'=>$size,
'dropbox_revision'=>$revision,
);
$message=$this->input->post('subject');
//for slack call
if(isset($message)){
$message=$message;
$messageType = "Knowledge_center";
$this->send_messages->send_message_on_slack($messageType);
}
//echo "<pre>" . print_r($data, true) . "</pre>";
$insert_res = $this->knowledge_model->insert_rec($data);
if ($insert_res != "conf") {
if ($insert_res == "subject") {
$this->session->set_flashdata('message', "<p>Subject Name already exist.Please change Subject</p>");
} else {
$this->session->set_flashdata('message', "<p>Error in Insertion.</p>");
}
echo '<script>window.location.href = "' . base_url() . 'knowledge/add";</script>';
} else {
$this->session->set_flashdata('message', "<p>Record added successfully.</p>");
echo '<script>window.location.href = "' . base_url() . 'knowledge";</script>';
}
} else {
//set the flash data error message if there is one
$this->data['message'] = (validation_errors() ? validation_errors() : $this->session->flashdata('message'));
$this->data['subject'] = array(
'name' => 'subject',
'class' => 'form-control round-input',
'id' => 'subject',
'placeholder' => 'Subject',
'type' => 'text',
'autofocus' => 'true',
'data-required' => '1',
'value' => $this->form_validation->set_value('subject'),
);
$this->data['tagdata'] = array(
'name' => 'tagsar',
'class' => 'form-control tags tags-input',
'id' => 'tagsar',
'type' => 'text',
'autofocus' => 'true',
'data-type' => 'tags',
'value' => $this->form_validation->set_value('tagsar'),
);
$data['desc'] = $this->form_validation->set_value('description');
// $data['dropbox']=$this->dropbox->dp();
$msg = "";
$data['title'] = 'Knowledge Center';
$data['msg'] = $msg;
$this->load->view('includes/header', $data);
$this->load->view('includes/sidebar', $data);
$this->load->view('add_knowledge', $this->data);
$this->load->view('includes/footer');
}
}
public function view($id)
{
$update_rec = $this->knowledge_model->get_rec_byid($id);
$data['dropbox_detail']=array(
"dropbox_rev"=> $update_rec[0]->dropbox_rev,
"dropbox_mim_type"=> $update_rec[0]->dropbox_mim_type,
"dropbox_path"=> $update_rec[0]->dropbox_path,
"dropbox_filesize"=> $update_rec[0]->dropbox_filesize,
"dropbox_revision"=> $update_rec[0]->dropbox_revision,
);
$data['subject_data'] = $update_rec[0]->subject;
$data['tags_data'] = unserialize($update_rec[0]->tags);
$data['desc'] = $update_rec[0]->description;
$data['title'] = 'Knowledge Center';
$this->load->view('includes/header', $data);
$this->load->view('includes/sidebar', $data);
$this->load->view('view_knowledge', $this->data);
$this->load->view('includes/footer');
}
public function manage_notify()
{
$notifyid = $_POST["elid"];
$notifytext = $_POST["notifytext"];
$notify_rec = $this->knowledge_model->get_notifyrec_byid($notifytext);
$ret_res = "<ul>";
foreach ($notify_rec as $notify_record) {
$ret_res .= "<li>" . $notify_record->subject . "</li>";
}
$ret_res .= "</ul>";
echo $ret_res;
exit;
}
public function update($id)
{
//validate form input
$this->form_validation->set_rules('subject', 'subject', 'required');
$this->data['message'] = (validation_errors() ? validation_errors() : $this->session->flashdata('message'));
$update_rec = $this->knowledge_model->get_rec_byid($id);
//echo "<pre>".print_r($update_rec[0],true)."</pre>";exit;
$seralizedtags = serialize($this->input->post('tagsar'));
if ($this->form_validation->run() == true) {
$session_data = $this->session->all_userdata();
$user_id = $session_data["userid"];
$data = array(
'edit_by_userid' => $user_id,
'subject' => $this->input->post('subject'),
'tags' => $seralizedtags,
'description' => $this->input->post('description')
);
$recid = $this->input->post('recid');
// echo "<pre>".print_r($data,true)."</pre>";exit;
$update_res = $this->knowledge_model->update_rec($recid, $data);
if ($update_res > 0) {
$this->session->set_flashdata('message', "<p>Record Updated successfully.</p>");
echo '<script>window.location.href = "' . base_url() . 'knowledge";</script>';
} else {
$this->session->set_flashdata('message', "<p>Error in Updation.</p>");
echo '<script>window.location.href = "' . base_url() . 'knowledge/update/' . $recid . '";</script>';
}
} else {
//set the flash data error message if there is one
$this->data['message'] = (validation_errors() ? validation_errors() : $this->session->flashdata('message'));
if (isset($update_rec)) {
$this->data['recid'] = array(
'name' => 'recid',
'class' => 'form-control',
'id' => 'recid',
'type' => 'hidden',
'autofocus' => 'true',
'data-required' => '1',
'value' => $update_rec[0]->id,
);
$this->data['subject'] = array(
'name' => 'subject',
'class' => 'form-control round-input',
'id' => 'subject',
'placeholder' => 'Subject',
'type' => 'text',
'autofocus' => 'true',
'data-required' => '1',
'value' => $update_rec[0]->subject,
);
$tags_data = unserialize($update_rec[0]->tags);
$this->data['tagdata'] = array(
'name' => 'tagsar',
'class' => 'form-control tags tags-input',
'id' => 'tagsar',
'type' => 'text',
'autofocus' => 'true',
'data-type' => 'tags',
'value' => $tags_data,
);
$data['desc'] = $update_rec[0]->description;
} else {
$this->session->set_flashdata('message', "<p>Update Record not found.</p>");
echo '<script>window.location.href = "' . base_url() . 'knowledge";</script>';
}
$msg = "";
$data['title'] = 'Knowledge Center';
$data['msg'] = $msg;
$this->load->view('includes/header', $data);
$this->load->view('includes/sidebar', $data);
$this->load->view('edit_knowledge', $this->data);
$this->load->view('includes/footer');
}
}
public function download_dbx_file(){
$file_path = $_POST['dropbox_path'];
$mime_type = $_POST['dropbox_mim_type'];
$this->download_file($file_path,$mime_type);
}
public function del($id)
{
$this->knowledge_model->del_rec($id);
$this->session->set_flashdata('message', "<p>Record Deleted successfully.</p>");
redirect(base_url() . 'knowledge');
}
// for upload to dropbox //
function getAppConfig()
{
global $appInfoFile;
try {
$appInfo = dbx\AppInfo::loadFromJsonFile($this->appInfoFile);
}
catch (dbx\AppInfoLoadException $ex) {
throw new Exception("Unable to load \"$this->appInfoFile\": " . $ex->getMessage());
}
$clientIdentifier = "examples-web-file-browser";
$userLocale = null;
return array($appInfo, $clientIdentifier, $userLocale);
}
function getClient()
{
if (!isset($_SESSION['access-token'])) {
return false;
}
list($appInfo, $clientIdentifier, $userLocale) = $this->getAppConfig();
$accessToken = $_SESSION['access-token'];
return new dbx\Client($accessToken, $clientIdentifier, $userLocale,$appInfo->getHost());
}
function getWebAuth()
{
list($appInfo, $clientIdentifier, $userLocale) = $this->getAppConfig();
$redirectUri = getUrl("dropbox-auth-finish");
$csrfTokenStore = new dbx\ArrayEntryStore($_SESSION, 'dropbox-auth-csrf-token');
return new dbx\WebAuth($appInfo, $clientIdentifier, $redirectUri, $csrfTokenStore, $userLocale);
}
function respondWithError($code, $title, $body = "")
{
$proto = $_SERVER['SERVER_PROTOCOL'];
header("$proto $code $title", true, $code);
echo renderHtmlPage($title, $body);
}
function getUrl($relative_path)
{
if (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') {
$scheme = "https";
} else {
$scheme = "http";
}
$host = $_SERVER['HTTP_HOST'];
$path = getPath($relative_path);
return $scheme."://".$host.$path;
}
function getPath($relative_path)
{
if (PHP_SAPI === 'cli-server') {
return "/".$relative_path;
} else {
return $_SERVER["SCRIPT_NAME"]."/".$relative_path;
}
}
function init()
{
global $argv;
// If we were run as a command-line script, launch the PHP built-in web server.
if (PHP_SAPI === 'cli') {
launchBuiltInWebServer($argv);
assert(false);
}
if (PHP_SAPI === 'cli-server') {
// For when we're running under PHP's built-in web server, do the routing here.
return $_SERVER['SCRIPT_NAME'];
}
else {
// For when we're running under CGI or mod_php.
if (isset($_SERVER['PATH_INFO'])) {
return $_SERVER['PATH_INFO'];
} else {
return "/";
}
}
}
function launchBuiltInWebServer($argv)
{
// The built-in web server is only available in PHP 5.4+.
if (version_compare(PHP_VERSION, '5.4.0', '<')) {
fprintf(STDERR,
"Unable to run example. The version of PHP you used to run this script (".PHP_VERSION.")\n".
"doesn't have a built-in web server. You need PHP 5.4 or newer.\n".
"\n".
"You can still run this example if you have a web server that supports PHP 5.3.\n".
"Copy the Dropbox PHP SDK into your web server's document path and access it there.\n");
exit(2);
}
$php_file = $argv[0];
if (count($argv) === 1) {
$port = 5000;
} else if (count($argv) === 2) {
$port = intval($argv[1]);
} else {
fprintf(STDERR,
"Too many arguments.\n".
"Usage: php $argv[0] [server-port]\n");
exit(1);
}
$host = "localhost:$port";
$cmd = escapeshellarg(PHP_BINARY)." -S ".$host." ".escapeshellarg($php_file);
$descriptors = array(
0 => array("pipe", "r"), // Process' stdin. We'll just close this right away.
1 => STDOUT, // Relay process' stdout to ours.
2 => STDERR, // Relay process' stderr to ours.
);
$proc = proc_open($cmd, $descriptors, $pipes);
if ($proc === false) {
fprintf(STDERR,
"Unable to launch PHP's built-in web server. Used command:\n".
" $cmd\n");
exit(2);
}
fclose($pipes[0]); // Close the process' stdin.
$exitCode = proc_close($proc); // Wait for process to exit.
exit($exitCode);
}
public function upload_to_dropbox($filename){
if($filename != ''){
try {
$dbxClient = $this->getClient();
$remoteDir = "/";
if (isset($_POST['folder'])) $remoteDir = $_POST['folder'];
$remotePath = rtrim($remoteDir, "/")."/".$filename;
$fp = fopen($_FILES['attached_file']['tmp_name'], "rb");
$result = $dbxClient->uploadFile($remotePath, dbx\WriteMode::add(), $fp);
fclose($fp);
//$str = print_r($result, true);
return $result;
} catch (Exception $e) {
echo $e->getMessage();
exit;
}
}
else{
echo "File does not exists";
exit;
}
}
public function download_file($file_path,$file_mime_type){
if($file_path != '' && $file_mime_type != '' ) {
try {
$dbxClient = $this->getClient();
$path = $file_path;
$fd = tmpfile();
$metadata = $dbxClient->getFile($path, $fd);
header("Content-Type: $metadata[mime_type]");
fseek($fd, 0);
fpassthru($fd);
fclose($fd);
} catch (Exception $e) {
echo $e->getMessage();
exit;
}
}
else{
echo "Invalid Request";
exit;
}
}
}
I am using codeigniter form validation lib and for some reason form is not updating this particular row. And there for not redirecting when form Submitted.
On my controller I use function like this
$this->load->model('admin/setting/model_setting');
$config_meta_title = $this->model_setting->edit_meta_title($this->input->post('config_meta_title'));
if (!empty($config_meta_title)) {
$data['config_meta_title'] = $this->input->post('config_meta_title');
} else {
$data['config_meta_title'] = $this->configs->get('config_meta_title');
}
But not updating database.
Model
<?php
class Model_setting extends CI_Model {
public function edit_meta_title() {
$data = array(
'group' => "config",
'key' => "config_meta_title",
'value' => $this->input->post('config_meta_title')
);
$this->db->where('setting_id', "2");
$this->db->update('setting', $data);
}
}
Controller
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Setting extends MY_Controller {
public function __construct() {
parent::__construct();
$this->lang->load('admin/setting/setting', 'english');
$this->lang->load('admin/english', 'english');
if ($this->session->userdata('user_id') == true) {
return true;
} else {
redirect('admin');
}
}
public function index() {
$this->load->library('form_validation');
$data['text_yes'] = $this->lang->line('text_yes');
$data['text_no'] = $this->lang->line('text_no');
$data['entry_meta_title'] = $this->lang->line('entry_meta_title');
$data['entry_maintenance'] = $this->lang->line('entry_maintenance');
$data['button_save'] = $this->lang->line('button_save');
$data['button_cancel'] = $this->lang->line('button_cancel');
$data['tab_store'] = $this->lang->line('tab_store');
$data['action'] = site_url('admin/setting');
$data['logout'] = site_url('admin/logout');
$data['cancel'] = site_url('admin/dashboard');
$this->load->model('admin/setting/model_setting');
$config_meta_title = $this->model_setting->edit_meta_title($this->input->post('config_meta_title'));
if (!empty($config_meta_title)) {
$data['config_meta_title'] = $this->input->post('config_meta_title');
} else {
$data['config_meta_title'] = $this->configs->get('config_meta_title');
}
if ($this->form_validation->run() == FALSE) {
return $this->load->view('setting/settings', $data);
} else {
redirect('admin/dashboard');
}
}
}
In your model, kindly try to pass it as a parameter:
public function edit_meta_title($config_meta_title) {
$data = array(
'group' => "config",
'key' => "config_meta_title",
'value' => $config_meta_title,
);
$this->db->where('setting_id', "2");
$this->db->update('setting', $data);
return $this->db->affected_rows();
}
I have fixed my issues now All working perfect
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Setting extends MY_Controller {
public function __construct() {
parent::__construct();
$this->lang->load('admin/setting/setting', 'english');
$this->lang->load('admin/english', 'english');
if ($this->session->userdata('user_id') == true) {
return true;
} else {
redirect('admin');
}
}
public function index() {
$data = array();
$data['text_yes'] = $this->lang->line('text_yes');
$data['text_no'] = $this->lang->line('text_no');
$data['entry_meta_title'] = $this->lang->line('entry_meta_title');
$data['entry_template'] = $this->lang->line('entry_template');
$data['entry_maintenance'] = $this->lang->line('entry_maintenance');
$data['button_save'] = $this->lang->line('button_save');
$data['button_cancel'] = $this->lang->line('button_cancel');
$data['tab_store'] = $this->lang->line('tab_store');
$data['action'] = site_url('admin/setting');
$data['logout'] = site_url('admin/logout');
$data['cancel'] = site_url('admin/dashboard');
$this->load->model('admin/setting/model_setting');
if (empty($config_meta_title)) {
$data['config_meta_title'] = $this->configs->get('config_meta_title');
}
if (empty($config_template)) {
$data['config_template'] = $this->configs->get('config_template');
}
$data['templates'] = array();
$directories = glob(APPPATH . 'modules/catalog/views/theme/*', GLOB_ONLYDIR);
foreach ($directories as $directory) {
$data['templates'][] = basename($directory);
}
if (empty($config_maintenance)) {
$data['config_maintenance'] = $this->configs->get('config_maintenance');
}
$this->load->library('form_validation');
$this->form_validation->set_rules('config_meta_title', 'Meta Title');
$this->form_validation->set_rules('config_template', 'Template');
$this->form_validation->set_rules('config_maintenance', 'Maintenance');
if ($this->form_validation->run() == FALSE) {
return $this->load->view('setting/settings', $data);
} else {
$config_meta_title = $this->model_setting->edit_meta_title($this->input->post('config_meta_title'));
$config_template = $this->model_setting->edit_template($this->input->post('config_template'));
$config_maintenance = $this->model_setting->edit_maintenance($this->input->post('config_maintenance'));
redirect('admin/dashboard');
}
}
}
Model
<?php
class Model_setting extends CI_Model {
public function edit_maintenance($config_maintenance) {
$data = array(
'group' => "config",
'key' => "config_maintenance",
'value' => $config_maintenance,
);
$this->db->where('setting_id', "1");
$this->db->update('setting', $data);
}
public function edit_meta_title($config_meta_title) {
$data = array(
'group' => "config",
'key' => "config_meta_title",
'value' => $config_meta_title,
);
$this->db->where('setting_id', "2");
$this->db->update('setting', $data);
}
public function edit_template($config_template) {
$data = array(
'group' => "config",
'key' => "config_template",
'value' => $config_template,
);
$this->db->where('setting_id', "3");
$this->db->update('setting', $data);
}
}
I'm working on task manager where have 2 types of user: Administrators(all privileges), and Users(limited privileges).
Here's my task function in controller
function task($id) {
$data = array(
'query' => $this->main_model->get_task($id),
'task_id' => $id,
);
$data2['comments'] = $this->main_model->get_comments($id);
$this->load->library('form_validation');
$this->load->helper('security');
$this->form_validation->set_rules('comment_text', 'comment_text', 'trim|required|strip_tags|xss_clean');
if ($this->form_validation->run() === FALSE)
{
if($this->main_model->get_task($id))
{
foreach ($this->main_model->get_task($id) as $tas)
{
$data = array(
'title' => $tas->task_name,
'desc' => $tas->task_description,
'date_created' => $tas->date,
'date_started' => $tas->task_start_date,
'deadline' => $tas->task_deadline,
'creator' => $tas->task_creator,
'owner' => $tas->task_owner,
'attach'=>$tas->attachment_name,
'status'=>$tas->task_status,
'priority'=>$tas->task_priority,
'task_id'=>$tas->ID_task,
'base_url' => base_url()
);
}
$data1 = array(
'emps' => $this->main_model->get_employees(),
'creator' => $this->main_model->get_details($id),
'owner' => $this->main_model->get_owner($id)
);
if ($this->session->userdata('employee_type') == 3) {
$qu = $this->main_model->permission();
$id = $this->session->userdata('id');
$id_emp = $this->uri->segment(3);
//foreach ($qu as $q) {
if (in_array($id, $qu[0]) && in_array($id_emp, $qu[0])) {
$this->load->view('task', array_merge($data, $data1, $data2));
}
else {
echo "No Permission to access this task";
}
}
}
}
else
{
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'doc|docx|pdf|txt|text|rtf|jpg|gif|png';
$config['max_size'] = '1024';
$this->load->library('upload', $config);
if (!$this->upload->do_upload()) {
if ("You did not select a file to upload." != $this->upload->display_errors('','')) {
$error = array('error' => $this->upload->display_errors());
$this->load->view('task', $error);
}
else {
$this->main_model->set_comments($id);
redirect(current_url());
}
}
else {
$data = array('upload_data' => $this->upload->data());
$data1 = $this->upload->data();
$data2 = $data1['file_name'];
$this->main_model->set_comments($id);
$this->main_model->set_attachment($id, $data2);
redirect(current_url());
}
}
}
and my permission function in model:
function permission() {
$query = $this->db->get('employees_tasks');
$ret = $query->result_array();
return $ret;
}
What I'm trying to do is, get all data from database employee_tasks check if the ID_task and ID_employee are in the same row in database, but I can't get it working, I only getting first row of database, not the others, and that's my key problem, get all rows from db.
I tried query database with result, result_array, row, row_array, but for some reason everything is listing only first row in db. Any Help would be appreciated.
To get all results from a separate table using codeigniter Active record you can do like this
function permission() {
$this->db->select("*");
$this->db->from("employees_tasks");
$this->db->where('id', 'your id');
$query = $this->db->get();
return $query->result();
// OR
$query = $this->db->query("SELECT * from employees_tasks WHERE your condition");
return $query->result();
}
Hope it makes sense
When i try to update the query in php- codeigniter I get this form_validation error. Here is my Controller
THIS gives me error and I am not able to update or add an entry into my database
<?php
class Person extends CI_Controller {
// num of records per page
private $limit = 15;
function Person() {
parent::__construct();
//$this->load->library('table','form_validation');
$this->load->library('table');
$this->load->library('form_validation');
$this->form_validation->set_rules();
$this->load->helper('url');
$this->load->model('personModel', '', TRUE);
}
function index($offset = 0) {
$uri_segment = 3;
$offset = $this->uri->segment($uri_segment);
// load data
$persons = $this->personModel->get_paged_list($this->limit, $offset)->result();
// have pagntn
$this->load->library('pagination');
$config['base_url'] = site_url('person/index/');
$config['total_rows'] = $this->personModel->count_all();
$config['per_page'] = $this->limit;
$config['uri_segment'] = $uri_segment;
$this->pagination->initialize($config);
$data['pagination'] = $this->pagination->create_links();
// generate table data
$this->load->library('table');
$this->table->set_empty(" ");
$this->table->set_heading('No', 'Name', 'Gender', 'Education',
'Date of Birth (dd-mm- yyyy)', 'Interest', 'Actions');
$i = 0 + $offset;
foreach ($persons as $person) {
$this->table->add_row(++$i, $person->name, strtoupper($person->gender) ==
'M' ? 'Male' : 'Female', ($person->education),
date('d-m-Y', strtotime($person->dob)), ($person->interest),
anchor('person/view/' . $person->id, 'view', array('class' => 'view',
'onclick' => "return confirm('View Full Details?')")) . ' ' .
anchor('person/update/' . $person->id, 'update', array('class' => 'update')) . ' ' .
anchor('person/delete/' . $person->id, 'delete', array('class' =>
'delete', 'onclick' => "return confirm('Are you sure want to delete this person?')"))
);
}
$data['table'] = $this->table->generate();
$this->load->library('table');
$this->load->library('form_validation');
// load view
$this->load->view('personList', $data);
}
function add() {
// set validation propert/ies
$this->set_fields();
// set common properties
$data['title'] = 'Add new person';
$data['message'] = '';
$data['action'] = site_url('person/addPerson');
$data['link_back'] = anchor('person/index/', 'Back to list of persons',
array('class' => 'back'));
// load view
$this->load->view('personEdit', $data);
}
function addPerson() {
// set common properties
$data['title'] = 'Add new person';
$data['action'] = site_url('person/addPerson');
$data['link_back'] = anchor('person/index/', 'Back to list of persons',
array('class' => 'back'));
// set validation properties
$this->set_fields();
$this->set_rules();
// run validation
if ($this->form_validation->run() == FALSE) {
$data['message'] = '';
} else {
// save data
$person = array('name' => $this->input->post('name'),
'gender' => $this->input->post('gender'),
'dob' => date('Y-m-d', strtotime($this->input->post('dob'))));
$id = $this->personModel->save($person);
// set form input name="id"
$this->form_validation->id = $id;
// set user message
$data['message'] = '<div class="success">add new person success</div>';
}
// load view
$this->load->view('personEdit', $data);
}
function view($id) {
// set common properties
$data['title'] = 'Person Details';
$data['link_back'] = anchor('person/index/', 'Back to list of persons',
array('class' => 'back'));
// get person details
$data['person'] = $this->personModel->get_by_id($id)->row();
// load view
$this->load->view('personView', $data);
}
function update($id) {
// set validation properties
$this->set_fields();
// prefill form values
$person = $this->personModel->get_by_id($id)->row();
$this->form_validation->id = $id;
$this->form_validation->name = $person->name;
$_POST['gender'] = strtoupper($person->gender);
$this->form_validation->dob = date('d-m-Y', strtotime($person->dob));
// set common properties
$data['title'] = 'Update person';
$data['message'] = '';
$data['action'] = site_url('person/updatePerson');
$data['link_back'] = anchor('person/index/', 'Back to list of persons',
array('class' => 'back'));
// load view
$this->load->view('personEdit', $data);
}
function updatePerson() {
// set common properties
$data['title'] = 'Update person';
$data['action'] = site_url('person/updatePerson');
$data['link_back'] = anchor('person/index/', 'Back to list of persons',
array('class' => 'back'));
// set validation properties
$this->set_fields();
$this->set_rules();
// run validation
if ($this->form_validation->run() == FALSE) {
$data['message'] = '';
} else {
// save data
$id = $this->input->post('id');
$person = array('name' => $this->input->post('name'),
'gender' => $this->input->post('gender'),
'dob' => date('Y-m-d', strtotime($this->input->post('dob'))),
'education'=>$this->input->post('education'),
'interest'=>$this->input->post('interest'));
$this->personModel->update($id, $person);
// set user message
$data['message'] = '<div class="success">update person success</div>';
}
// load view
$this->load->view('personEdit', $data);
}
function delete($id) {
// delete person
$this->personModel->delete($id);
// redirect to person list page
redirect('person/index/', 'refresh');
}
// validation fields
function set_fields() {
$fields['id'] = 'id';
$fields['name'] = 'name';
$fields['gender'] = 'gender';
$fields['dob'] = 'dob';
$fields['education']='educaiton';
$fields['interest']='
$this->form_validation->set_fields('$fields');
//echo"hellofff";
//exit;
}
// validation rules
function set_rules() {
$rules['name'] = 'trim|required';
$rules['gender'] = 'trim|required';
$rules['dob'] = 'trim|required|callback_valid_date';
$rules['education']='trim|required';
$rules['interest']='trim|required';
$this->form_validation->set_rules($rules);
$this->form_validation->set_message('required', '* required');
$this->form_validation->set_message('isset', '* required');
$this->form_validation->set_error_delimiters('<p class="error">', '</p>');
}
function form_validation() {
$this->add();
}
// date_validation callback
function valid_date($str) {
if (!ereg("^(0[1-9]|1[0-9]|2[0-9]|3[01])-(0[1-9]|1[012])-([0-9]{4})$", $str)) {
$this->form_validation->set_message('valid_date', 'date format is not
valid. dd-mm-yyyy');
return false;
} else {
return true;
}
}
}
?>
This is my model:
PersonMOdel: Database name is employeeregistration and tableused is tbl_person
<?php
class PersonModel extends CI_Model {
// table name
private $tbl_person= 'tbl_person';
function Person(){
parent::construct();
}
// get number of persons in database
function count_all(){
return $this->db->count_all($this->tbl_person);
}
// get persons with paging
function get_paged_list($limit = 15, $offset = 0){
$this->db->order_by('id','asc');
return $this->db->get($this->tbl_person, $limit, $offset);
}
// get person by id
function get_by_id($id){
$this->db->where('id', $id);
return $this->db->get($this->tbl_person);
}
// add new person
function save($person){
$this->db->insert($this->tbl_person, $person);
return $this->db->insert_id();
}
// update person by id
function update($id, $person){
$this->db->where('id', $id);
$this->db->update($this->tbl_person, $person);
}
// delete person by id
function delete($id){
$this->db->where('id', $id);
$this->db->delete($this->tbl_person);
}
}
?>
This can be cossidered a CRUD application.