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

Multiple ignore-fields for is_unique-function

$
0
0
I'm having some issues with the Codeigniter 4 validation rules. I'm using the is_unique function within the ruleset in Order to except one single row from the validation.
The problem here is that there are two fields in the table that need to be checked:

Code:
'episodeTitle' => [
                    'label' => 'episodeTitle',
                    'rules' => 'required|max_length[100]|is_unique[episodes.episodeTitle,episodes.episodeID,' . $episodeID . ',episodes.podcastID,' . $podcastID . ']',
                    'errors' => [
                        'required' => lang('Errors.nested.episode.episodeTitleRequired'),
                        'max_length' => lang('Errors.nested.messages.maxLength100'),
                        'is_unique' => lang('Errors.nested.episode.episodeTitleUnique'),
                    ],
                ],

Is it possible, to make the exception depending on 2 or more fields?
I want to check the episodeID AND the podcastID not only one of these values.

composer require get error in centos 7

$
0
0
hi all.

i have my project in CI4 working ok in my VPS (centos 7). Recently, i'm trying to emplement new report funciton, in that function, i need to use PHPSpreadsheet to export data to excel ( https://phpspreadsheet.readthedocs.io/en...ng-started

in my localhost, i run the installation script: composer require phpoffice/phpspreadsheet and it work oki in my localhost

but when i upload my code to the live version, and run the installation script above, i got this error message:

 
Quote:Script bash admin/setup.sh handling the post-update-cmd event returned with error code 127
Installation failed, reverting ./composer.json and ./composer.lock to their original content.

You can see full error in the image below
does anyone have this problem? and how to fix it pls.

.png   Screenshot_29.png (Size: 44.13 KB / Downloads: 0)

getPost() not working as expected

$
0
0
Hi,
I have a simple process in my controller, however if the POST of form input 'first_name' is empty, the statement if($this->request->getPost('first_name') ) is evaluated FALSE and (of course) an exception is reported as $data['employee_data']['first_name'] does not exist.

Is this how request->getPost() is supposed to work for empty form input fields?

This is quite annoying especially if the form input firld is optional !


PHP Code:
if($this->request->getGet('emp_no')){
    $data['emp_no']=$this->request->getGet('emp_no');
    $data['employee_data']=$em->getEmployeeById($this->request->getGet('emp_no'));
    
}else{
    if($this->request->getPost('emp_no')){
        $data['emp_no']=$this->request->getPost('emp_no');
    }
}
            
if ($this->request->getPost('first_name')) {                
    $data['first_name'] =$this->request->getPost('first_name'FILTER_SANITIZE_STRING);
}else{            
    $data['first_name'] = $data['employee_data']['first_name'];

Problem with CodeIgniter\Database\BaseBuilder->select ()

$
0
0
Saludos.



Estoy utilizando CI 4 en una aplicación local que usa mysql 5.7.3.

Todas las queries funcionan con normalidad en local y la aplicación trabaja muy bien.

Ahora he clonado la aplicación en un vps y ninguna querie que lleve select a menos que comente la linea.

Es decir, si yo hago



PHP Code:
public function getTest(){
~
  31        $query $this->builderTest->select('*');
~
  32         $test $this->builderTest->get();
~
  33         echo json_encode($test->getResultArray());
~
  34     
 



That will work fine on localhost, but it won't work on the vps (which is connected to the same database).
In vps I must do:



PHP Code:
public function getTest(){
~
  31       // $query = $this->builderTest->select('*');
~  32         $test $this->builderTest->get();
~
  33         echo json_encode($test->getResultArray());
~
  34     



(continue..)

Issue Maintaining Logged in State

$
0
0
We are encountering a strange situation where accessing pages in one specific area of the site causes the user to get logged out. I have reviewed the code for those pages and they do not touch cookies except to check logged in status. That is necessary as logged in users see a different result from others. Clearing the cache in Chrome does not help but I think it ignores the do not cache headers. The following is sent with every page:

"header('Cache-Control: no-cache, no-store, must-revalidate');header('Pragma: no-cache');header('Expires: 0')"

 What is more strange is this only happens with Chrome. It does not occur with Firefox or Edge. 

 If anyone has encountered this did you find a magic meta tag which resolved it?

How to set variable in .env file programity

$
0
0
Hello,
I want to set database variable and some custom variable like license key to my .env file programmity. How can I do that?

ADEL Codeigniter 4 CRUD generator

$
0
0
ADEL CODEIGNITER 4 CRUD GENERATOR

ADEL CCG is an easy open-source intuitive web app to create AdminLTE3 -Bootstrap 4- dashboards with CRUD operations in php.
The CRUD application is able to manage data from any MySQL database, however complex the structure and volume of data are.
It ships with powerful API, Controller, Model, View generator to speed up the development of your CMS, CRM or other back-office system.





[Image: 6eQOlV9.png][Image: Jb3gxs2.png][Image: ppuMReh.png]

https://github.com/adelbak/Codeigniter-4-CRUD-generator

ENJOY

CI3 - Session not save

$
0
0
Hello,

I have move an old project to new server and i have an problem with session on codeigniter 3.
My session is not save.
I use database for store my session.


I have remark that in my cookie my value change each time that i reload page, but my cookie is well inserted in database.


My config

PHP Code:
$config['base_url'] = 'https://192.168.1.35/';


$config['sess_driver']             'database';
$config['sess_cookie_name']        'ci_session';
$config['sess_save_path']          'ci_sessions';
$config['sess_expiration']         7200;
$config['sess_match_ip']           true;
$config['sess_time_to_update']     300;
$config['sess_regenerate_destroy'] = false;

$config['cookie_prefix']   '';
$config['cookie_domain']   '';
$config['cookie_path']     '/';
$config['cookie_secure']   false;
$config['cookie_httponly'] = false

My Code
PHP Code:
class Login extends MY_Controller
{

    public function __construct()
    {
        parent::__construct();
        $this->data['pageCourante'] = 'login';
        $this->layout->set_theme('login');
    }

    public function index()
    {
        $this->load->library('session');

        var_dump($this->session->userdata('test'));

        echo '<br>';

        $this->session->set_userdata('test'5645);

        var_dump($this->session->userdata('test'));
        exit();
    

Tanks for your help

how to pass flashdata as data inside a view that will be returned as data

$
0
0
my view implementation is such that all my views are passed as data to rendered on a general template. however sometimes i also need to pass data inside these views that are to be returned as views.

for example

PHP Code:
public function myview()
{
  $_SESSION['error] = 'this is an error';
  $this->session->mark_as_flash('
error');
  
  //creating the view
  //this is the page that will be passed as data
  $page_content['
content'] = $this->$this->load->view('example-folder/example-page', $example-data, TRUE);
  
  //this is the template layout page
  $this->load->view('
nurse/home', $page_data);

My question is how do i pass the flashdata to be rendered in the $page_content['content']?

Why can't I pass this variable to a Twig view?

$
0
0
I am working on a online newspaper/blogging application with CodeIgniter 3.1.8 and Bootstrap 4. I have decided to add themes to it. The application is not HMVC, only MVC.

The themes directory is outside application as can be see in the image below:
[Image: syL0A.jpg]
Inside themes I have the theme directory (of course) which contains the "master view", 

Code:
layout.php
:
[Image: gOGzZ.jpg]
How I use the theme views


In application/core I have added a MY_Loader.php file with the following contents:

Code:
<?php defined('BASEPATH') OR exit('No direct script access allowed');

class MY_Loader extends CI_Loader {

function theme_view($folder, $view, $vars = array(), $return = FALSE) {
  $this->_ci_view_paths = array_merge($this->_ci_view_paths, array(FCPATH . $folder . '/' => TRUE));
   return $this->_ci_load(array(
    '_ci_view' => $view,
    '_ci_vars' => $this->_ci_prepare_view_vars($vars),
    '_ci_return' => $return
   ));
  }
}


In my Posts controller's index() method, I load the view passing it the data:

Code:
public function index() {
  //more code here
  $data['posts'] = $this->Posts_model->get_posts($config['limit'], $config['offset']);
  $this->load->theme_view('/themes/caminar/', 'layout', $data);
}


Using Twig for the themes


The next step was to add the [i]Twig[/i] template engine to the theme(s). For this purpose, I use CodeIgniter Simple and Secure Twig. I have:
  • Added the [i]Simple and Secure Twig[/i] library in application\libraries


  •  In the third_party directory I have added Twig itself.


  • In application\config\autoload.php I have loaded twing:
    $autoload['libraries'] = array('database', 'form_validation', 'session', 'user_agent', 'twig');

  • Set the path for the Twig views in application\libraries\Twig.php:
Code:
private $config = [ 'paths' => [FCPATH . '/themes', VIEWPATH], 'cache' => '/path/to/twig/cache', ];

The problem

According to the docs of CodeIgniter Simple and Secure Twig, we can set a global variable like so: 

Code:
$this->twig->addGlobal('sitename', 'My Awesome Site');

So, I added 
Code:
$this->twig->addGlobal('siteTitle', 'My Awesome Site');

 in the Posts controller:
Code:
public function index() {

//call initialization method
$config = $this->_initPagination("/", $this->Posts_model->get_num_rows());

$data = $this->Static_model->get_static_data();
$data['pages'] = $this->Pages_model->get_pages();
$data['categories'] = $this->Categories_model->get_categories(); 

//use limit and offset returned by _initPaginator method
$data['posts'] = $this->Posts_model->get_posts($config['limit'], $config['offset']);
$this->twig->addGlobal('siteTitle', 'My Awesome Site');
$this->load->theme_view('/themes/caminar/', 'layout', $data);
}

Yet, in themes\caminar\layout.php the line <title>{{siteTitle}}</title>
 
does not display "My Awesome Site" inside the <title> tag.
What am I doing wrong?

"POST" requestnot working on a real host

$
0
0
I have a problem with post request. On my localhost every codes run well also POST request. As for on a real host POST requests not working. Dont understand why?
Here is my html codes
<form  action="<?php echo base_url()."/ayarlar/guncelle" ?>" method="post" enctype="multipart/form-data" >
<div class="form-group">
         <label>Web Sitesi İsmi</label>
         <input type="text" class="form-control"  placeholder="Web Sitesi İsmi" name="siteismi" value=""/>

</div>
<div class="form-group mb-0">
       <div>
             <button type="submit" class="btn btn-primary waves-effect waves-light mr-1">
                    Güncelle
             </button>
       </div>
</div>

</form>

by the way at config.php public $baseURL = 'http://www.catidekorasyon.com/panel';

Controllers/ayarlar.php

<?php namespace App\Controllers;

class Ayarlar extends BaseController
{

public $viewFolder="";

    public function __construct()
    {
            parent::__construct();

            $this->viewFolder = "ayarlar_v";
            $this->ayarlarModel = model('App\Models\AyarlarModel'false);
            $this->session=session();

       
    }


public function guncelle()
    {


        $viewData = new \stdClass();
        $viewData->viewFolder = $this->viewFolder;


        helper(['form''url','tools','Text']);
        $validation = \Config\Services::validation();

        $siteismi=$this->request->getPost("siteismi");
    

        print_r($siteismi);
        die();


}


and result is 

Array
(
)



What are your opinions








                            

WHERE-LIKE and problem for build search-engin in western movie web app

$
0
0
Mean thanks for allowing me to retrieve values in get with the statement $ search = $ this-> input-> get, I'm trying to use the same method for an internal search engine in my western film library but I can't find the key to the problem. In the Model di CI versione 3.0 I put:

MODEL:

   function estrai($search)
{

$query= $this->db->select('*')
->from('western')
->where('anno')
->like('anno', '$search')
->get();
return $query->result();
}

VIEW:

    public function mostramodulo()
  {
    $search = $this->input->get('search');
    $data['result'] = $this->western_model->estrai($search);
    $this->load->view('western/mostramodulo', $data);
}

I have a form with a text field and a submit which sends data on the text which has the name search. the information is sent correctly because in url I see:

/index.php/home/mostramodulo?search=Ford&search=


but the result is a blank page so I tried to print the value in transit which should become $ search with ECHO but it confirms my doubts is that there is no value inside and therefore I cannot graphically build the page because the model does not work.

but when i try to view the page i see the message

Severity: Notice

Message: Undefined variable: search

Filename: western/mostramodulo.php

do you have any suggestions to be able to extract from the engine the name of a director or the year in which the film was shot with subsequent materialization of the data sought? Thanks for any tips, I'm at the beginning and not framed everything well, on the CI 3 documentation I did not find the use of the LIKE linked to WHERE clear to me

.png   engine.png (Size: 65.36 KB / Downloads: 0)

Is it impossible to redirect back or to another route with POST method request?

$
0
0
I got an error when I wanted to redirect back with a 404 error. So I created a route 1 url with 3 different HTTP requests. I want to redirect with the POST request method but the return one is always GET method request. Is it impossible to redirect back using the POST method?

My bad experience with CI

$
0
0
Hello, i have couple days since i try to learn this framework.I choose this because in my opinion is the most light and fast framework (the rest is very hard to learn).  So, after i decided to start coding i tried to make a sample auth with email and password.

Offcourse, first i searched on google for "codeigniter 4 login" , to see the strategy from other people. I choose this one and in time while watching, i start to coding in my old Netbeans.[url=https://github.com/alexlancer/codeigniter4login][/url]

I got the idea with MVC (model working with databases, view mean what user see, and controller is between the two).

So, i created Login Controller, UserModel and Login Page.   Everything working, i make some rules for login page (mysite/login), i created a database, i make the connection , and other stuff like this.

The problem begin ...

In my new login controller i have this rule : 'password' => 'required|min_length[3]|max_length[255]|validateUser[email,password]',
everything ok untill i got the error like  this validateUser not found.So, i'm looking on github in that page, and i see a folder Validation which i don't have it.I start to looking on git and i created the folder, with new .php file UserRules.php  like this:

Code:
<?php
namespace App\Validation;
use App\Models\UserModel;

class UserRules
{

  public function validateUser(string $str, string $fields, array $data){
    $model = new UserModel();
    $user = $model->where('email', $data['email'])
                  ->first();

    if(!$user)
      return false;

    return password_verify($data['password'], $user['password']);
  }
}


I opened config/Validation.php and i register this rule, i think ...  Confused public $ruleSets = [ \App\Validation\UserRules::class,etc

AND ???? what is the point??

So, this code get back in userModel  and ask about email....and after that, ask about password...I am already little angry.


In userModel i have this two functions 
PHP Code:
  protected function beforeInsert(array $data){
    $data $this->passwordHash($data);
    $data['data']['created_at'] = date('Y-m-d H:i:s');

    return $data;
  }

  protected function beforeUpdate(array $data){
    $data $this->passwordHash($data);
    $data['data']['updated_at'] = date('Y-m-d H:i:s');
    return $data;
  

But i don't see anywhere to call this functions...or maybe are autoloaded ?but how ?

So, in less 5 minutes i was blocked...I must to create controller, model and view.Also to set routes, to create that validation folder, to register that validate function, to walk like a zombie between folders and try to get the point....But i don't get it, and i'm tired.

For eg., why i must to complicate the world and make a folder validation with file, to register that and bla bla when is very simple to make just : 

Code:
where name=name and password=password (eg.)
login ok and redirect

else
name or password wrong
in controller.Or just a function in model (checkUser($name,$pass))
Maybe someone explain me, maybe that login code from git is bad..or not.If is not why must to make so complicated??? Huh Confused

PHP 7.4.12 Released!

$
0
0
PHP 7.4.12. This is a bug fix release.

using a query result in another query binding?

$
0
0
I've done a sql query and I get a structure called query2. I'd like to use the item (coding) to search a different table. 



Code:
$query2 = {CI_DB_mysqli_result} [8]
conn_id = {mysqli} [19]
result_id = {mysqli_result} [5]
result_array = {array} [0]
result_object = {array} [1]
  0 = {stdClass} [1]
   item = "coding"

But when I do the following I get an error "Object of class stdClass could not be converted to string". Can I cast it to a string? I'd like $item to be "coding". 
Code:
             $item=$query2->result();

             $sql3 = "SELECT a.qualified
                      FROM standard_activities sa, relation r, activity a WHERE sa.activity=? AND sa.id=a.id";
             $query3=$this->db->query($sql3, array($item));
How can I get the binding SQL to work?

[Newbie] Help me how to call Soap webservice for CI 3.x

$
0
0
I'm a newbie. I have a soap webservice and my work is calling soap in CI.
my code
public function checklogin()
{
$masv=$this->input->post('masv');
$password=$this->input->post('password');
$client = new SoapClient('http://daotao.nuce.edu.vn:8085/WebService1.asmx?WSDL');
        $result = $client->__soapcall("Login",array('masv'=>$masv,'password'=>$password));
        var_dump($result);
}

althought my user and password are true,  my result alway returns false.
Can you have me? Thanks you Heart Heart Heart

Visual bootstrap editor

$
0
0
I have been reworking my website from a visual perspective and have been coding all the html by hand.

 Today, I started wondering if a visual editor for bootstrap might speed this up and ensure the base html is correctly written. I have Dreamweaver as part of my Adobe subscription, but do not like using it.

 I spotted something called Bootstrap Studio, which looks interesting.

 However, I would really like to hear from others about their experiences with this and other visual editors.

Confusion with .env and config files

$
0
0
Hello

I am confused with the new addition in CI4, the .env file. 
Should I use the .env file for the baseURL or I should use the App/Config.php?

Which configuration prevails?

.env file has 
Code:
app.baseURL = 'http://mydomain.test',

but the Config/App.php file also has:

Code:
public $baseURL = 'http://localhost:8080/';


Also, the .env file has Database settings, but so does the Config/Database.php

Confusion goes further:

.env file has:
 
Code:
encryption.key = 'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855'


but the Config/Encryption.php has the:

Code:
public $key = 'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855';


So, which one should I use? The .env file, or the Config files? Which one is preferred for real-life apps
which will be deployed to the clients, but I will have to have them on my localhost as well, for support purposes?


Any advice will be deeply appreciated.

csv upload+form input data+ajax+button onclick

$
0
0

.png   jac.png (Size: 10.25 KB / Downloads: 7)
.png   jac.png (Size: 10.25 KB / Downloads: 7)
.png   jac.png (Size: 10.25 KB / Downloads: 7)
.png   jac.png (Size: 10.25 KB / Downloads: 7)
.png   jac.png (Size: 10.25 KB / Downloads: 7)
.png   jac.png (Size: 10.25 KB / Downloads: 7) Hi everyone,
 
Pls help me to solve my problem.

I always get alert "ERROR in ADDING MARKS"
Developer tool says "Failed to load response data"

this is my view form



Code:
<form action="#" class="form-horizontal" id="form_upload_marks" >                                
                            
                                   <div class="form-group">
                                    <label class="col-sm-2 control-label">Subject</label>
                                    <div class="col-sm-4">                                  
                <select class="form-control" name = "subject" id = "subject">
                  <option value="-1">--- SELECT Subject ---</option>
                  <?php foreach ($all_assigned_courses as $row2) {?>
    <?php  $sel = $row2->id == $subject ? 'selected' : NULL;  ?>
    <option value="<?php echo $row2->id; ?>" <?php echo $sel; ?> ><?php echo $row2->course_code." - ". $row2->course_name; ?></option>                
                  <?php } ?>
                </select>                                   
                                    </div>          
                                   </div>
                                

                                   <div class="form-group">
                                   <label class="col-sm-2 control-label">Year</label>
                                    <div class="col-sm-2"><input type="text" class="form-control"  name="yea" id="yea" /></div>
                                    </div>


                                   <br>  
                                    <div class="form-group">
                                    <label class="col-sm-2 control-label">File Upload</label>
                                    <div class="col-sm-2"><input type="file" name="userfile" ><br><br></div>
                                    </div>
                                    <br><br>
                             </form>

                                  
        <div class="form-group"><label class="col-sm-5 control-label">
          <button type="button" class="btn btn-default" id="btn_add_emp" onClick="add_marks()"> &nbsp;UPLOAD</button>
          <button type="button" class="btn btn-default" id="btn_add_cancel"> &nbsp;CANCEL</button>         
        </div>   
 


ajax part
Code:
  function add_marks()
    {   
 var subject = $('#subject').val();
 var yea = $('#yea').val();
      
    var form = $('#form_upload_marks')[0];
    var formData = new FormData(form);
   
        show_loading();
          $.ajax({
            url : "<?php echo site_url('index.php/Level_co/import_marks')?>/"+subject+"/"+yea,    
            type: "POST",
            data: formData,
            contentType: false,
            processData: false,
            dataType: "JSON",
           
            success: function(data)
            {
                 if(data.status)
                        {             
                           location.reload();
                        }
                         else
                        {
                            hide_loading();
                            for (var i = 0; i < data.inputerror.length; i++)
                            {
                                $('[name="'+data.inputerror[i]+'"]').parent().parent().addClass('has-error'); //select parent twice to select div form-group class and add has-error class
                                $('[name="'+data.inputerror[i]+'"]').next().text(data.error_string[i]); //select span help-block class set text error string
                            }
                        }
            },
            error: function (jqXHR, textStatus, errorThrown)
            {
               
                alert('ERROR in ADDING MARKS');
            }
        });    
    }



this is my controller
PHP Code:
function import_marks($subject,$yea) {
$yea=$this->input->post('yea');
$subject=$this->input->post('subject');

    $this->load->model('Login_model');
                      
    $allowed 
=  array('csv');
    $filename $_FILES['userfile']['name'];
    $ext pathinfo($filenamePATHINFO_EXTENSION);                    
                        
                        
if(in_array($ext,$allowed) ) {
                        
                $file 
$_FILES['userfile']['tmp_name'];
                $handle fopen($file"r");
                $c 0;//
                while(($row fgetcsv($handle1000",")) !== false)
                {
                                $data = array(
                                    'student_id'  => $row[0],                                   
                                    
'mark' => $row[1],
                                    'course_id ' => $subject,
                                    'myear'  => $yea
                                                                                                                                                                        
                                         
); 

                    if($c<>0){                    //SKIP THE FIRST ROW
                    $result=$this->Login_model->insert_csv_marks($data);
                    }

                    $c $c 1;
                }
                                           if($result){
                                             $this->session->set_flashdata('message_ok''Csv Data Imported Successfully');
                                             redirect('Level_co/marks');
                                             
                                           
}
                                           else{
                                              $this->session->set_flashdata('message_error''Error in CSV data importing');
                                               redirect('Level_co/marks');   
                                           
}
                             
                        
} else {
                       $this->session->set_flashdata('message_error''Upload only CSV File ');
                 redirect(base_url().'Level_co/marks');   
                        
}    
    
            


this is my model

PHP Code:
function insert_csv_marks($data) {
        $this->db->insert('mark'$data);
       return $this->db->insert_id(); 
      
Viewing all 14069 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>