Quantcast
Channel: CodeIgniter Forums - All Forums
Viewing all 14150 articles
Browse latest View live

route value can be used in URL

$
0
0
Hi,

I've just discovered that the route value can be used in a url e.g. This route

Code:
$route['products/get/all'] = "main/getAllProducts";

can be run with example.com/products/get/all or example.com/main/getAllProducts


Is this by design?
Or, have I done something wrong?
Is there a way I serve a 404 if a user uses the route value?

Assignment Operator := breaks the query builder

$
0
0
I am try to create this query using the query builder

Code:
SELECT *, (@no:=@no+1) AS no FROM user WHERE user.deleted = 0
 but by using the Codeigniter 4 query builder but it returns the query as 

Code:
SELECT *, (@no:=@no+1) AS no FROM `user` WHERE `user`.`deleted` = :user.deleted:

This is the code I used to this
Code:
$this->builder = $this->db->table('user');
$this->builder->select('*, (@no:=@no+1) AS no');
$this->builder->where("user.deleted", 0);

Extract data from CommVault, Netbackup and EMC Data Domain

$
0
0
I want to create a web application where I can extract the data from CommVault (hkrtrainings.com/commvault-training), NetBackup and Data Domain Backups and insert them into a thrid backup client such as Rubrik. Is there any way I can do that using a program? Are there API's available for this?

It seems all these providers provide GUI based services and none exposed as code. I did find CommVault SDK which can enable me to browse contents and possibly save data. It would be great help if there could be pointers to others.

Why unknow column 'slug_safelink' ?

$
0
0
I have problem Unknown column 'slug_safelink' in 'where clause'

Controller :
Code:
<?php namespace App\Controllers;
use App\Models\Safelink_model;

class Safelink extends BaseController
{
    public function index()
    {
        /**
        * Load Module
        */
        $Safelink_model = new Safelink_model();

        $data['data'] = $Safelink_model->getData();
        $data['config'] = $this->settings;
        $data['recaptchaWidget'] = $this->recaptcha->getWidget();
        $data['recaptchaScript'] = $this->recaptcha->getScriptTag();
        $data['pesan_gagal'] = $this->session->getFlashdata('inputs');
        $data['error_gagal'] = $this->session->getFlashdata('errors');
        $data['pesan_berhasil'] = $this->session->getFlashdata('success');

        $data['errlog'] = $this->session->getFlashdata('errlog');

        echo view('link/header', $data);
        echo view('link/home', $data);
        echo view('link/footer', $data);
    }

    // Save Data
    public function simpan()
    {
        /**
        * Load Module
        */
        $Safelink_model = new Safelink_model();

        $namaP = esc($this->request->getPost('nama'));
        $slugP = esc($this->request->getPost('slug'));
        $urlP = esc($this->request->getPost('url'));
        $captcha = $this->request->getPost('g-recaptcha-response');

        $validationForm = [
            'nama' => $namaP,
            'slug' => $slugP,
            'url' => $urlP
        ];

        if($this->form_validation->run($validationForm, 'safelink') == FALSE){
            // mengembalikan nilai input yang sudah dimasukan sebelumnya
            $this->session->setFlashdata('inputs', $this->request->getPost());
            // memberikan pesan error pada saat input data
            $this->session->setFlashdata('errors', $this->form_validation->getErrors());
            // kembali ke halaman form
            return redirect()->to(base_url('link'));
        } else {
            $response = $this->recaptcha->verifyResponse($captcha);
            if (isset($response['success']) AND $response['success'] === true) {
                /**
                * Success Verify Anti Bot
                */
                // Apa yang mau disimpan
                $data = [
                    'kode_safelink' => NULL,
                       'nama_safelink' => $namaP,
                       'slug_safelink' => $slugP,
                    'url_safelink' => $urlP,
                    'hits_safelink' => NULL,
                    'created_safelink' => now()
                ];

                $simpan = $Safelink_model->saveData($data);
                    
                if ($simpan) {
                    $this->session->setFlashdata('success', 'Simpan Data Berhasil!');
                    // kembali ke halaman utama
                    return redirect()->to(base_url('link'));
                } else {
                    // memberikan pesan error pada saat input data
                    $this->session->setFlashdata('errors', 'Simpan Data Gagal!');
                    // kembali ke halaman form
                    return redirect()->to(base_url('link'));
                }
            } else {
                // memberikan pesan error pada saat input data
                $this->session->setFlashdata('errors', 'Captcha gagal!');
                // memberikan data input
                $this->session->setFlashdata('inputs', $this->request->getPost());
                // kembali ke halaman form
                return redirect()->to(base_url('link'));
            }
        }
    }
}


Models :
Code:
<?php namespace App\Models;
use CodeIgniter\Model;

class Safelink_model extends Model
{
    protected $table = 'safelink';
    protected $primaryKey = 'kode_safelink';
    
    public function getData($id = null)
    {
        if($id === null){
            return $this->findAll();
        } else {
            return $this->getWhere(['kode_safelink' => $id]);
        }  
    }

    public function saveData($data)
    {
        $query = $this->db->table($this->table)->insert($data);
        return $query;
    }

    public function updateData($data, $id)
    {
        $query = $this->db->table($this->table)->update($data, array('kode_safelink' => $id));
        return $query;
    }

    public function deleteData($id)
    {
        $query = $this->db->table($this->table)->delete(array('kode_safelink' => $id));
        return $query;
    }
}

Structure Table :
Code:
CREATE TABLE `safelink` (
  `kode_safelink` int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
  `nama_safelink` varchar(80) NOT NULL UNIQUE,
  `slug_safelink` text NOT NULL,
  `url_safelink` text NOT NULL,
  `hits_safelink` bigint NOT NULL DEFAULT '0',
  `created_safelink` datetime NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;


.png   Capture.PNG (Size: 87.64 KB / Downloads: 4)

Formatting REST response in JSON

$
0
0
So, I'm trying to follow the docs here:

https://codeigniter.com/user_guide/incom...stful.html

In my extended ResourceController I'm setting $format = 'json', but I always get XML.

I've run through the code of ResourceController.php, ResponseTrait.php and Negotiate.php and I can see nowhere where this property is actually used to decide the response format!

As it stands it seems like the headers are always used to determine the response.

Can anyone confirm or explain where I may have messed up?

Here's the relevant code:

<?php namespace App\Controllers;

use CodeIgniter\RESTful\ResourceController;

class Salutation extends ResourceController
{
    protected $modelName = 'App\Models\SalutationModel';
    protected $format    = 'json';

    public function index()
    {
        // print '<pre>'; print_r($this->model->asArray()->findAll()); exit;
        // $this->setFormat("json");
        return $this->respond($this->model->findAll());
    }


 

Use $dateFormat INT in models

$
0
0
Reading the documentation of CodeIgniter4 (Models), i found this.

[Image: CFyIn.png]




I tried use a timestamps with a type date of int, but this not working because at updated the column "updated_at" it is 0. My model is:

PHP Code:
<?php namespace App\Models;

use 
CodeIgniter\Model;

class 
UserModel extends eCrisisModel{

    protected $table 'user';
    protected $primaryKey 'id';
   
    
protected $returnType 'array';
    protected $useSoftDeletes true;

    protected $allowedFields = ["login""pass""about_me""utc"];

    protected $useTimestamps true;
    protected $createdField 'created_at';
    protected $updatedField 'updated_at';
    protected $deletedField 'deleted_at';
    protected $dateFormat 'int';
}

?>


The eCrisisModel is a abstract class extends of Model class:

PHP Code:
<?php namespace App\Models;


use 
CodeIgniter\Model;


// existentialCrisis

abstract class eCrisisModel extends Model{


    protected $prefix '';

    protected $exists false;

    protected $builder;

public function 
__construct(...$params){

parent::__construct(...$params);

        //"I am therefore I think"

        if(!$this->db->tableExists($this->prefix.$this->table)){

$this->creatingMe();

            $this->exists true;

}

        $this->builder $this->db->table($this->table);

}


public function 
creatingMe(){

        //...

}

}


?>



The controller where it is executed is:

PHP Code:
<?php namespace App\Controllers;


use 
CodeIgniter\Controller;


class 
Test extends Controller{


    public function __construct(){

$this->UserModel model('App\Models\UserModel');

$this->SettingModel model('App\Models\SettingModel');

    }


    public function index(){

$data = [
        'login' => 'jiji',
        'pass'  => password_hash("passss",PASSWORD_DEFAULT),
        'about_me'  => 'xd',
        'utc' => -2.75
];


$this->UserModel->builder->where('id'1);

$this->UserModel->builder->update($data);

    }

}


?>


And the database after of the update is:

[Image: 6JZDF.png]



Which is my error ? why the system not recording the update timestamp?






(The link of this problem in StackOverflow is: https://stackoverflow.com/questions/6462...4_64624957)

Having trouble connecting to mysql database

$
0
0
Hello,

I want to connect MySQL community server, but I keep getting this error message over and over:8

CodeIgniter\Database\Exceptions\DatabaseException #8

Unable to connect to the database.


This is the code:

$custom = [
    'DSN'      => '',
    'hostname' => 'localhost',
    'username' => 'root',
    'password' => 'root',
    'database' => 'world',
    'DBDriver' => 'MySQLi',
    'DBPrefix' => '',
    'pConnect' => false,
    'DBDebug'  => (ENVIRONMENT !== 'production'),
    'cacheOn'  => false,
    'cacheDir' => '',
    'charset'  => 'utf8',
    'DBCollat' => 'utf8_general_ci',
    'swapPre'  => '',
    'encrypt'  => false,
    'compress' => false,
    'strictOn' => false,
    'failover' => [],
    'port'    => 3306,
];

$db = \Config\Database::connect($custom);
$db->query("SELECT * FROM city");
$db->close();


Any kind of help would be appreciated

Problem Extending Database Driver

$
0
0
Hi,

Just followed the wiki (https://github.com/bcit-ci/CodeIgniter/w...se-Drivers) and im getting this error:

Quote:Fatal error: Uncaught Error: Call to undefined method MY_DB_mysqli_driver::where() in /system/libraries/Session.php on line 218
Error: Call to undefined method MY_DB_mysqli_driver::where() in /system/libraries/Session.php on line 218


On line 218 of /system/libraries/Session.php:

PHP Code:
$this->CI->db->where('session_id'$session['session_id']); 

My extended class is just the example from the wiki:

PHP Code:
<?php
class MY_DB_mysqli_driver extends CI_DB_mysqli_driver
{
    public function __construct($params)
    {
        parent::__construct($params);
        log_message('debug''Extended DB driver class instantiated!');
    }

    public function get_first($table)
    {
        return $this->limit(1)->get($table);
    }



Can anyone help? 

Im using CI 2.x

Thanks

Problem with custom validation

$
0
0
Hello all. 

I'm new to CI4. I'm really excited about the new way of coding. I use CI3 for the last 6 years. 

I began to rewriite an application from CI3 to CII4 but I stack with a problem using custom validation.

I have added my custom validation file in App\Config\Validation.php

Code:
    public $ruleSets = [
        \CodeIgniter\Validation\Rules::class,
        \CodeIgniter\Validation\FormatRules::class,
        \CodeIgniter\Validation\FileRules::class,
        \CodeIgniter\Validation\CreditCardRules::class,
        \App\Validation\VisitorAreasRules::class,
    ];

This is the VisitorsAreaRules.php. The password in the db is not encrypted, is just varchar for now. That's why I don't use password_verify.
Code:
<?php

namespace App\Validation;

use App\Models\VisitorAreasModel;

class VisitorAreasRules {

  public function validateVisitor (string $str, string $fields, array $data): bool  {
    $visitorAreasModel = new VisitorAreasModel();
    $visitor = $visitorAreasModel->where('username', $data['username'])
                                 ->where('pass', $data['password'])
                                 ->first();
    if (!$visitor) {
      return false;
    }
    return true;
  } // validateVisitor()
} // class


And this is my class
Code:
<?php namespace App\Controllers\World\Parents;

use App\Models\VisitorAreasModel;
use CodeIgniter\Controller;

class Login extends Controller
{
  public function index($alias = false)
  {
    $data = [];
    helper(['form']);

    $data['page_title'] = 'Parents Area';

    if ($this->request->getMethod() == 'post') {
      // Validation rules
      $rules = [
        'username'  => 'required',
        'password'  => 'required|validateVisitor(username, password)'
      ];

      $errors = [
        'password' => [
          'validateVisitor' => 'Invalid username or password'
        ]
      ];

      if (! $this->validate($rules, $errors)) {
        $data['validation'] = $this->validator;
      }
      else {
        $visitorAreasModel = new VisitorAreasModel();
      }
    }

    return view('public/parents/login', $data);

  } // index()
} // class

It returns the bellow error:
validateVisitor(username, password) is not a valid rule.

Please, can anyone tell me what I do wrong?

Thank you in advance.

codeigniter 3.1.9 is compatible with 7.4

$
0
0
Does codeigniter 3.1.9 version is compatible with 7.4?

Dedicated thread for Country, maybe?

$
0
0
Was wondering if its possible to have a dedicated thread or sub-forum with country specific threads.

It would act as a contact point to develop a local community for any country. Just a thought [Image: smile.png] Tongue

order_by() how to use NULLS LAST in active records

$
0
0
I am using Potgresql with Codeigniter3 and i have query that have null values in some columns that i need to use for order_by() on those columns.

When i tried to run this query in pgAdmin it works and moving null values on last place, which is fine

Code:
SELECT a.*, b.*, c.*
FROM accounts a
LEFT JOIN subscriptions b ON a.id = b.provider_account_id AND b.subscriber_account_id = 10
JOIN users c ON c.email = a.name
WHERE a.user_role = 0
ORDER BY b.following DESC NULLS LAST, b.last_updated DESC NULLS LAST


result
Code:
-----------------------------------
| following | last_updated        |
-----------------------------------
| 1         | 2020-11-04 11:08:44 |
-----------------------------------
| 0         | 2020-11-04 11:22:07 |
-----------------------------------
| null      | null                |
-----------------------------------



here is query from model which doesn't put nulls on last place

Code:
$this->db->select('a.*, b.*, c.*');
$this->db->from('accounts a');
$this->db->join('subscriptions b', 'a.id = b.provider_account_id AND b.subscriber_account_id = '.$client_id, 'left');
$this->db->join('users c', 'c.email = a.name');
$this->db->where('a.user_role', 0);
$this->db->order_by('b.following', 'desc');
$this->db->order_by('b.last_updated', 'desc');

result

Code:
-----------------------------------
| following | last_updated        |
-----------------------------------
| null      | null                |
-----------------------------------
| 1         | 2020-11-04 11:08:44 |
-----------------------------------
| 0         | 2020-11-04 11:22:07 |
-----------------------------------

how i can implement NULLS LAST in active record in codeigniter in order_by() function

Database Migrate Problem

$
0
0
Hi everyone,

I'm try to use myth-auth, in my local machine it work fine, i run php spark migrate -all, and migrate controller, both work fine on my local machine. The problem is on my production server, i cant use ssh to run cli, and i try migrate controller but doesnt work, i have try this 2 codes on the controller.


PHP Code:
try{
      $migrate->setNamespace('Myth\Auth')->latest();      //this code work on my local machine



and this other


PHP Code:
try{
      $migrate->latest();



Do I need some other configuration on my production server?

Best regards.

Error Codeigniter PHP could not open the stream: Rights denied

$
0
0
I have been working on a project that uses tokens. I work on it in Windows 7 and it is fine, but after I ported this project on Ubuntu to work on it there, It gives me this error in every page / control / method that I try try to access:

Code:
Warning: require_once(/opt/lampp/htdocs/TS_Project/system/core/CodeIgniter.php): failed to open stream: Permission denied in /opt/lampp/htdocs/TS_Project/index.php on line 202

Code:
Fatal error: require_once(): Failed opening required '/opt/lampp/htdocs/TS_Project/system/core/CodeIgniter.php' (include_path='.:/opt/lampp/lib/php') in /opt/lampp/htdocs/TS_Project/index.php on line 202

The CodeIgniter.php file does not exist, the path to it is correct and I can read and write in it (I can open it in a text editor and modify it freely). I tried changing file permissions using chmod command but nothing happened. Why is permissions denied in the CodeIgniter.php file?

Codeigniter 4: Get value from BaseController to custom helper

$
0
0
Seems get_instance() is no longer working in Codeigniter 4. But I need to get some value from BaseController to my custom_helper. Here is my code snippet:
BaseController.php
Code:
<?php namespace App\Controllers;
class BaseController extends Controller
{
protected $helpers = ['custom'];
public function initController(...) {
  parent::initController(...);

  $myconfig = config('MyConfig');
  $this->languages = $myconfig->languages;
  $this->selected_lang = $myconfig->site_lang;
  $lang_segment = $this->request->uri->getSegment(1);
  foreach ($this->languages as $lang) {
    if ($lang_segment == $lang->short_form) {
      $this->selected_lang = $lang;
      $this->lang_base_url = base_url() . $lang->short_form . "/";
    }
  }
}
}
// Here I need to pass ($this->selected_lang) value to my custom_helper.

custom_helper.php
Code:
<?php
if (!function_exists('trans')) {
    function trans($string)
    {
        $language_translations = get_translation_array($this->selected_lang->id);
        // --> Here I want to get ($this->selected_lang->id) value from BaseController.
       
        if (!empty($language_translations[$string])) {
            return $language_translations[$string];
        }
        return "";
    }
}
function get_translation_array($land_id)
{
    .......
}

I'm not sure is it possible or not! I'm newbie in CI4. Please suggest if is there any solutions. Thanks in advance.

Upgrade From Version 2.1.3 To Version 3.1 or 4

$
0
0
Hi,

We have a RESTful web services API developed in CodeIgniter Version 2.1.3 and hosted of ISP server. Now our ISP want to upgrade the PHP and MySQL (to latest version) on that server and not sure if these upgrades will work with our CodeIgniter Application. We are in process of rewriting this application in some other language but still want to keep it up for next 3-4 years for backward compatibility for our existing customers. 

I will really appreciate if someone will help me to determine what's the best option for us to keep it running without having any issues for next 3-4 years with latest PHP and MySQL. We are not planning to do any new development to this site, except the regular maintenance and bug fixes. 

At this time I have following 3 options, but not sure which one is the best to keep my application running for next 3-4 years without any more interruptions:

Option 1 - Just upgrade PHP and MySQL and keep application running in CodeIgniter 2.1.3 (not sure if it's compatible or will create any issues)

Option 2 - Upgrade to Version 3, but in that case I have to go through multiple 3 migration process (from 2.1.3 to 2.1.4, 2.1.4 to 2.2.x and then 2.2.x to 3.0.x) - Preferred (but just need help about the steps involved)

Option 3 - Upgrade to Version 4, but in that case I have to pretty much rewrite the whole application as we have no plans to keep that application running after 3 -4 years therefore I think at this time Option 2 is the best option.

Thanks,
SauGo

how to get limited number of records and order by rand ?

$
0
0
Hi,

I am 100% new to CI 4 and fairly new to MVC.

I did the Build Your First Application and from that I am trying to make my project.

I created a homepage in which I have to load banners and using the example code from news tutorial I got all the banners but I want to get them randomly and also I want to limit the number of banners I get. Right now I am getting all findAll(); so according to this my question is:

1. How to get 5 banners randomly
2. How / Where (in which folder) to add custom js / css and other files ?

Thanks.

Image optimiser inside CI4 (such as TinyPNG)

$
0
0
Hello everyone,

I wonder if one of you already tried to implement an image optimizer such as TinyPNG inside codeigniter ?
It could be nice to optimize images "on the fly" directly in our content managers when we upload images.

TinyPNG is very efficient (much better than photoshop optimizer). It was first conceived as an online tool, but now could be implemented in several famous content management such as Drupal, Joomla and Wordpress : https://tinypng.com/third-party. It could be a nice tool inside CI4 but I don't know if we can adapt it easily. What do you think about it ?

isset

$
0
0
hi
im starter 

searched forum not found.

is there a substitute for isset (PHP) in CI4?

thank you

waiting

404s on Controller Methods

$
0
0
Working on migrating an app from v2 -> v3. 

In config.php: 
PHP Code:
$config['base_url'] = 'http://localhost/ci3';
$config['index_page'] = '';
$config['uri_protocol']    = 'REQUEST_URI'

My Login controller (controllers/Login.php):
PHP Code:
<?php
defined
('BASEPATH') OR exit('No direct script access allowed');
    class 
Login extends CI_Controller{
        public function 
index(){
            
$data['main_content'] = 'login_form';
            
$data['page_title'] = 'Login';
            
$this->load->view('includes/login_signup_template'$data);
        }

        public function 
forgot(){
            
//load a view that collects the user's email address
            
$data['main_content'] = 'registration/forgot_collect_email';
            
$data['page_title'] = 'Forgot Password';
            
$this->load->view('includes/login_signup_template'$data);
        }

    } 

In routes.php: 
PHP Code:
$route['default_controller'] = 'login';
$route['404_override'] = '';
$route['translate_uri_dashes'] = FALSE

SO: 
https://localhost/ci3 -> This loads my login page. 
https://localhost/ci3/login/forgot -> This gets a 404 

Any ideas on what I am doing wrong here? This is driving me nuts.
Viewing all 14150 articles
Browse latest View live


Latest Images