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

Basic understanding of returned values

$
0
0
Hi, 

i've create a first modell
with in this functon
"public function users_get_by_id(int $id, array $fields=array())
{
if(empty($fields)){ return $this->find($id); }
else
{ return $this->select($fields)->where('id', $id); }
}"

in controller i get and print out the returned values

" $data = $this->UsersModel->users_get_by_id(user_id(),['username','department_main']);
echo"<pre>";
print_r($data);"

now i wondering, why in my $data are not only the values from the tables/fields called by the "users_get_by_id" function. There are a lot more informations.

Example print_r($data)
"App\Models\UsersModel Object
(
[pager] =>
[db:protected] => CodeIgniter\Database\MySQLi\Connection Object
(
[DSN:protected] =>
[port:protected] => 3306
[hostname:protected] => ....
[username:protected] => ...
[password:protected] => ...
[database:protected] =>....
[DBDriver] => MySQLi
[subdriver:protected] =>
[DBPrefix:protected] =>
[pConnect:protected] =>
[DBDebug:protected] => 1
[charset:protected] => utf8mb4
[DBCollat:protected] => utf8mb4_general_ci
[swapPre:protected] =>
[encrypt:protected] =>
[compress:protected] =>
[strictOn:protected] =>
[failover:protected] => Array
(
)

[lastQuery:protected] => CodeIgniter\Database\Query Object
(
[originalQueryString:protected] => UPDATE `users` SET `last_active` = :last_active:
WHERE `id` = :id:
[finalQueryString:protected] => UPDATE `users` SET `last_active` = '2024-12-26 08:21:46'
WHERE `id` = 4
[binds:protected] => Array
(
[last_active] => Array
(
[0] => 2024-12-26 08:21:46
[1] => 1
)

[id] => Array
(
[0] => 4
[1] => 1
)

)

[bindMarker:protected] => ?
[startTime:protected] => 1735197706.5346
[endTime:protected] => 1735197706.6206
[errorCode:protected] =>
[errorString:protected] =>
[db] => CodeIgniter\Database\MySQLi\Connection Object
*RECURSION*
)

[connID] => mysqli Object
(
[affected_rows] => 1
[client_info] => mysqlnd 8.2.25
[client_version] => 80225
[connect_errno] => 0
[connect_error] =>
[errno] => 0
[error] =>
[error_list] => Array
(
)

[field_count] => 0
[host_info] => ...:3306 via TCP/IP
[info] => Rows matched: 1 Changed: 1 Warnings: 0
[insert_id] => 0
[server_info] => 8.0.33
[server_version] => 80033
[sqlstate] => 00000
[protocol_version] => 10
[thread_id] => 191645650
[warning_count] => 0
)

[resultID] => 1
[protectIdentifiers] => 1
[reservedIdentifiers:protected] => Array
(
[0] => *
)

[escapeChar] => `
[likeEscapeStr] => ESCAPE '%s'
[likeEscapeChar] => !
[pregEscapeChar:protected] => Array
(
[1] => `
[0] => `
[3] => `
[2] => `
)

[dataCache] => Array
(
)

[connectTime:protected] => 1735197706.5289
[connectDuration:protected] => 0.0016748905181885
[pretend:protected] =>
[transEnabled] => 1
[transStrict] => 1
[transDepth:protected] => 0
[transStatus:protected] => 1
[transFailure:protected] =>
[transException:protected] =>
[aliasedTables:protected] => Array
(
)

[queryClass:protected] => CodeIgniter\Database\Query
[dateFormat:protected] => Array
(
[date] => Y-m-d
[datetime] => Y-m-d H:iConfused
[datetime-ms] => Y-m-d H:iConfused.v
[datetime-us] => Y-m-d H:iConfused.u
[time] => H:iConfused
)

[deleteHack] => 1
[mysqli] => mysqli Object
(
[affected_rows] => 1
[client_info] => mysqlnd 8.2.25
[client_version] => 80225
[connect_errno] => 0
[connect_error] =>
[errno] => 0
[error] =>
[error_list] => Array
(
)

[field_count] => 0
[host_info] => ... via TCP/IP
[info] => Rows matched: 1 Changed: 1 Warnings: 0
[insert_id] => 0
[server_info] => 8.0.33
[server_version] => 80033
[sqlstate] => 00000
[protocol_version] => 10
[thread_id] => 191645650
[warning_count] => 0
)

[resultMode] => 0
[numberNative] =>
)

[insertID:protected] => 0
[DBGroup:protected] => globalDB
[returnType:protected] => array
[tempReturnType:protected] => array
[casts:protected] => Array
(
)

[castHandlers:protected] => Array
(
)

[converter:protected] =>
[protectFields:protected] => 1
[allowedFields:protected] => Array
(
[0] => username
[1] => status
[2] => status_message
[3] => active
[4] => last_active
)

[useTimestamps:protected] =>
[dateFormat:protected] => datetime
[createdField:protected] => created_at
[updatedField:protected] => updated_at
[useSoftDeletes:protected] => 1
[tempUseSoftDeletes:protected] => 1
[deletedField:protected] => deleted_at
[allowEmptyInserts:protected] =>
[updateOnlyChanged:protected] => 1
[validationRules:protected] => Array
(
)

[validationMessages:protected] => Array
(
)

[skipValidation:protected] =>
[cleanValidationRules:protected] => 1
[validation:protected] =>
[allowCallbacks:protected] => 1
[tempAllowCallbacks:protected] => 1
[beforeInsert:protected] => Array
(
)

[afterInsert:protected] => Array
(
)

[beforeUpdate:protected] => Array
(
)

[afterUpdate:protected] => Array
(
)

[beforeInsertBatch:protected] => Array
(
)

[afterInsertBatch:protected] => Array
(
)

[beforeUpdateBatch:protected] => Array
(
)

[afterUpdateBatch:protected] => Array
(
)

[beforeFind:protected] => Array
(
)

[afterFind:protected] => Array
(
)

[beforeDelete:protected] => Array
(
)

[afterDelete:protected] => Array
(
)

[table:protected] => users
[primaryKey:protected] => id
[useAutoIncrement:protected] => 1
[builder:protected] => CodeIgniter\Database\MySQLi\Builder Object
(
[resetDeleteData:protected] =>
[QBSelect:protected] => Array
(
[0] => username
[1] => department_main
)

[QBDistinct:protected] =>
[QBFrom:protected] => Array
(
[0] => `users`
)

[QBJoin:protected] => Array
(
)

[QBWhere:protected] => Array
(
[0] => Array
(
[condition] => id = :id:
[escape] => 1
)

)

[QBGroupBy] => Array
(
)

[QBHaving:protected] => Array
(
)

[QBKeys:protected] => Array
(
)

[QBLimit:protected] =>
[QBOffset:protected] =>
[QBOrderBy] => Array
(
)

[QBUnion:protected] => Array
(
)

[QBNoEscape] => Array
(
[0] => 1
[1] => 1
)

[QBSet:protected] => Array
(
)

[QBWhereGroupStarted:protected] =>
[QBWhereGroupCount:protected] => 0
[QBIgnore:protected] =>
[QBOptions:protected] =>
[db:protected] => CodeIgniter\Database\MySQLi\Connection Object
(
[DSN:protected] =>
[port:protected] => 3306
[hostname:protected] => 10.35.47.127:3306
[username:protected] => k84694_4u
[password:protected] => 4hkf$;3M37FaB
[database:protected] => k84694_4u
[DBDriver] => MySQLi
[subdriver:protected] =>
[DBPrefix:protected] =>
[pConnect:protected] =>
[DBDebug:protected] => 1
[charset:protected] => utf8mb4
[DBCollat:protected] => utf8mb4_general_ci
[swapPre:protected] =>
[encrypt:protected] =>
[compress:protected] =>
[strictOn:protected] =>
[failover:protected] => Array
(
)

[lastQuery:protected] => CodeIgniter\Database\Query Object
(
[originalQueryString:protected] => UPDATE `users` SET `last_active` = :last_active:
WHERE `id` = :id:
[finalQueryString:protected] => UPDATE `users` SET `last_active` = '2024-12-26 08:21:46'
WHERE `id` = 4
[binds:protected] => Array
(
[last_active] => Array
(
[0] => 2024-12-26 08:21:46
[1] => 1
)

[id] => Array
(
[0] => 4
[1] => 1
)

)

[bindMarker:protected] => ?
[startTime:protected] => 1735197706.5346
[endTime:protected] => 1735197706.6206
[errorCode:protected] =>
[errorString:protected] =>
[db] => CodeIgniter\Database\MySQLi\Connection Object
*RECURSION*
)

[connID] => mysqli Object
(
[affected_rows] => 1
[client_info] => mysqlnd 8.2.25
[client_version] => 80225
[connect_errno] => 0
[connect_error] =>
[errno] => 0
[error] =>
[error_list] => Array
(
)

[field_count] => 0
[host_info] => ::::3306 via TCP/IP
[info] => Rows matched: 1 Changed: 1 Warnings: 0
[insert_id] => 0
[server_info] => 8.0.33
[server_version] => 80033
[sqlstate] => 00000
[protocol_version] => 10
[thread_id] => 191645650
[warning_count] => 0
)

[resultID] => 1
[protectIdentifiers] => 1
[reservedIdentifiers:protected] => Array
(
[0] => *
)

[escapeChar] => `
[likeEscapeStr] => ESCAPE '%s'
[likeEscapeChar] => !
[pregEscapeChar:protected] => Array
(
[1] => `
[0] => `
[3] => `
[2] => `
)

[dataCache] => Array
(
)

[connectTime:protected] => 1735197706.5289
[connectDuration:protected] => 0.0016748905181885
[pretend:protected] =>
[transEnabled] => 1
[transStrict] => 1
[transDepth:protected] => 0
[transStatus:protected] => 1
[transFailure:protected] =>
[transException:protected] =>
[aliasedTables:protected] => Array
(
)

[queryClass:protected] => CodeIgniter\Database\Query
[dateFormat:protected] => Array
(
[date] => Y-m-d
[datetime] => Y-m-d H:iConfused
[datetime-ms] => Y-m-d H:iConfused.v
[datetime-us] => Y-m-d H:iConfused.u
[time] => H:iConfused
)

[deleteHack] => 1
[mysqli] => mysqli Object
(
[affected_rows] => 1
[client_info] => mysqlnd 8.2.25
[client_version] => 80225
[connect_errno] => 0
[connect_error] =>
[errno] => 0
[error] =>
[error_list] => Array
(
)

[field_count] => 0
[host_info] => ....:3306 via TCP/IP
[info] => Rows matched: 1 Changed: 1 Warnings: 0
[insert_id] => 0
[server_info] => 8.0.33
[server_version] => 80033
[sqlstate] => 00000
[protocol_version] => 10
[thread_id] => 191645650
[warning_count] => 0
)

[resultMode] => 0
[numberNative] =>
)

[tableName:protected] => users
[randomKeyword:protected] => Array
(
[0] => RAND()
[1] => RAND(%d)
)

[countString:protected] => SELECT COUNT(*) AS
[binds:protected] => Array
(
[id] => Array
(
[0] => 4
[1] => 1
)

)

[bindsKeyCount:protected] => Array
(
)

[canLimitDeletes:protected] => 1
[canLimitWhereUpdates:protected] => 1
[supportedIgnoreStatements:protected] => Array
(
[update] => IGNORE
[insert] => IGNORE
[delete] => IGNORE
)

[testMode:protected] =>
[joinTypes:protected] => Array
(
[0] => LEFT
[1] => RIGHT
[2] => OUTER
[3] => INNER
[4] => LEFT OUTER
[5] => RIGHT OUTER
)

[isLiteralStr:protected] => Array
(
)

[pregOperators:protected] => Array
(
)

[escapeChar:protected] => `
)

[tempData:protected] => Array
(
)

[escape:protected] => Array
(
)

[builderMethodsNotAvailable:CodeIgniter\Model:private] => Array
(
[0] => getCompiledInsert
[1] => getCompiledSelect
[2] => getCompiledUpdate
)

)"


Where are they from, is it normaly in ci4?

How can i reduse the returned value only to the values from the function?

By the way what it means and effects with the prepend parts like "[db:protected]" etc?

Thanks a lot to make it clear for me.

Where to store often used datas?

$
0
0
Hello,

I would like to discuss how best to handle data that is used frequently in the project.

For example (think about lot datas of this kind for example in a forum)
- User IDs, usernames
- Roleids, role names,
etc.

Normaly on every single point i run a database-query to get this infos.

I would like to reduce the database call for this simple data, especially because it normally doesn't change or rarely changes.

I'm thinking about storing all of these values in the session, but I'm not sure if that will have a positive impact on server cache etc?

Another idea was to use local browser storage. At this point I'm worried for safety reasons. Maybe users can change the values and paste those into the code etc?

What is your opinion or suggestion about this?

How rewite this

$
0
0
$file = @fopen($localFilePath, 'w');
                $ch = curl_init($FileDetails['href']);
                curl_setopt($ch, CURLOPT_FILE, $file);
                curl_setopt($ch, CURLOPT_HTTPHEADER, [ 'Authorization: OAuth ']);
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
                curl_setopt($ch, CURLOPT_HEADER, false);
                curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
                fwrite($file, curl_exec($ch));
                curl_close($ch);
                fclose($file);


how can i rewite this with  Services::curlrequest

i have a lot custum options is it possible or not?

And one more question how send CURLOPT_RETURNTRANSFER to true when i get quest via curlrequest i have headers

And i get image and insede body included headers, how can i remove it?

Load model in helper

$
0
0
hi,

i need to know if i have to load a wanted model in every helper function again and again or is there a way to load it once and how i can access them.

I try in my helper
"
Code:
use CodeIgniter\CodeIgniter;
use App\Models\Model;
use App\Models\DepartmentModel;

$Departmentmodel = model('DepartmentModel');

if (! function_exists('hlp_error_redirect'))
{
    function hlp_department_get(int $id,array $fields=array())
    {
        //Load needed Models
        $Departmentmodel = model('DepartmentModel');
        $res=$Departmentmodel->departments_get_by_id($id,$fields);  
        //$res=$this->Departmentmodel->departments_get_by_id($id,$fields);  
"

Info: the departmentmodel extend the model

Access with $this failed = Using $this when not in object context

What is the best way to load the model and make it accessable in the helper functions?

installazione CI4 su Aruba

$
0
0
Buonasera, 
uso correntemente Codeigniter 3 e 4 sulla rete aziendale con un server linux.
avendo un hosting Aruba in scadenza non più utilizzato, volevo provare ad installarlo on line, ho seguito la procedura per aggiungere applicazioni che utilizza Softaculous, la app dedicata per le installazioni, ma non va.
mi dice che ci sono stati troppi reindirizzamenti.
probabilmente sono le path da settare, ma gli errori non si vedono nonostante la configurazione development in .env
qualcuno ha esperienza in merito?
ricordo che tempo fa sempre per prova l'ho installato su un hosting diverso da Aruba ed ha funzionato tranquillamente.aculous
us[/url][u]Softaculous[/u]

[url=https://hosting.aruba.it/hosting/servizi-inclusi/softaculous-app-installer.aspx]

CodeIgniter v4.5.6 bug fix released!

Report post/user function not working

$
0
0
I didn't see a more appropriate forum for a post about the forum itself.

I tried reporting a user profile and specific posts, due to obvious spam links, but it didn't work. The report prompt asks for a reason with a dropdown that includes no values, and the report can't be submitted.

In case this is browser/environment specific, I'm using Brave 1.73.104 in Debian 12.

google cloud appengine standard run shield:setup

$
0
0
Hi all, 

I been able to get google cloud appengine working with CI4. 
I have a CI4 instance running, I can talk to a the cloud sql database, I can use the google API to talk to cloud storage. 
My application uses shield for authentication. GCP appengine has no console to SSH into to run shieldConfusedetup. 
How would I get this to work? Would I use the scripts directive in the composer.json? How would I answer the questions that are prompted in shieldConfusedetup process.

Thank you in advance for your time in responding

Basecontroller load helpers / library depend on loggedin

$
0
0
Hi,

i want to load different helper in case of a user is logged in (shield) or not.

For this i try to do it like this in my basecontroller:
Code:
if( auth()->loggedIn() )

        // Load helpers for logged-in users
        protected $helpers = ['helper1','helper2',...];
}
else
{
        protected $helpers = ['helper1'];
}

Result: "syntax error, unexpected identifier "auth", expecting "function" or "const""

It seems auth is not avivable at this part/moment?

Is there a way to do what i want - maybe also in the autoload-file?

Also i need to include a own library only if a user is logged in, if i have to do it in another way please let me know whats the difference to do it too.

Thanks to help and understanding ;-)

Route name problem

$
0
0
hi there are my routes :
Code:
$routes->group('admin_Locazioni_piani_viteria', ['filter' => 'permission:admin.access', 'namespace' => 'App\Controllers\Admin'], function ($routes) {
    $routes->match(['GET', 'POST'], 'inserisciRecord', 'Admin_locazioni_piani_viteria::inserisciRecord');
    $routes->match(['GET', 'PUT'], 'modificaRecord/(:num)', 'Admin_locazioni_piani_viteria::modificaRecord/$1');
    $routes->match(['GET', 'PUT'], 'rettifica_locazione_viteria/(:num)', 'Admin_locazioni_piani_viteria::rettifica_locazione_viteria/$1');
    $routes->match(['GET'], 'eliminaRecord/(:num)', 'Admin_locazioni_piani_viteria::eliminaRecord/$1');
    $routes->get('lista_completa', 'Admin_locazioni_piani_viteria::lista_completa');
    $routes->get('lista_locazioni_con_cartellino', 'Admin_locazioni_piani_viteria::lista_locazioni_con_cartellino');
    $routes->get('lista_locazioni_vuote', 'Admin_locazioni_piani_viteria::lista_locazioni_vuote');
    $routes->get('lista_locazioni_bloccate', 'Admin_locazioni_piani_viteria::lista_locazioni_bloccate', ['as' => 'admin_locazioni_bloccate']);
    $routes->get('lista_completa_ajax', 'Admin_locazioni_piani_viteria::lista_completa_ajax');
    $routes->get('get_data_from_ajax', 'Admin_locazioni_piani_viteria::get_data_from_ajax');
    $routes->get('togli_cartellino/(:num)', 'Admin_locazioni_piani_viteria::togli_cartellino/$1');
    $routes->get('metti_cartellino/(:num)', 'Admin_locazioni_piani_viteria::metti_cartellino/$1');
});

if i insert on my browser  : http://localhost:8080/admin_locazioni_bloccate

i have Can't find a route for 'GET: admin_locazioni_bloccate'.  why ?

Markdown Pages for CodeIgniter 4

$
0
0
This library allows you to use Markdown files as pages in your CodeIgniter 4 application. It dynamically converts Markdown content to HTML and serves it as web pages, making it ideal for static content like documentation or simple sites.

GitHub Repository: codeigniter-markdown-pages

Installation:
Code:
composer require michalsn/codeigniter-markdown-pages

Example Usage:
PHP Code:
$markdownPages  service('markdownpages'APPPATH 'Views/markdown');
$file $markdownPages->file('first-steps/second-file');
// returns "Second File"
$file->getName();
// returns parsed markdown
$file->parse()->getContent();
// returns parsed meta from YAML part of the file

$file->parse()->getMeta(); 

Docs:

https://michalsn.github.io/codeigniter-markdown-pages/

Tags for CodeIgniter 4

$
0
0
This library helps manage tags associated with various models, such as articles or products. It includes methods for adding, removing, and retrieving tags efficiently.

GitHub Repository: codeigniter-tags

Installation:
Code:
composer require michalsn/codeigniter-tags

Example Usage:
PHP Code:
model(ImageModel::class)->insert([
    'name'  => 'sampleFile.jpeg',
    'width'  => 100,
    'height' => 100,
    'tags'  => 'tag1,tag2,tag3',
]);

// Get tags for the image
model(ImageModel::class)->withTags()->find(1);

// Get images which have 'tag1' and 'tag2' assigned

model(ImageModel::class)->withAllTags(['tag1''tag2'])->findAll(); 

You don’t have to modify your models at all. Tags support is added automatically.

Docs:
https://michalsn.github.io/codeigniter-tags/

Signed URLs for CodeIgniter 4

$
0
0
This library generates and validates signed URLs, ensuring secure and temporary access (optionally) to resources while preventing URL manipulation.

GitHub Repository: codeigniter-signed-url

Installation:
Code:
composer require michalsn/codeigniter-signed-url

Example Usage:
PHP Code:
service('signedurl')->siteUrl('controller/method');
// will generate URL similar to:
// https://example.com/controller/method?query=string&signature=signature-goes-here
// or

service('signedurl')->setExpiration(HOUR)->urlTo('namedRoute''param');
// will generate URL similar to:
// https://example.com/route/name/12?expiration=1671980371&signature=signature-goes-here 

It comes with a filter to easily validate the signed URL.

Docs:
https://michalsn.github.io/codeigniter-signed-url/

In-model content translations for CodeIgniter 4

$
0
0
This library makes it easier to manage in-model translations for multilingual applications. It integrates with CodeIgniter's model system and allows for storing translations in a separate table while keeping the base entity intact. It provides a simple skeleton generator to kick-start the process.

GitHub Repository: codeigniter-translatable

Installation:
Code:
composer require michalsn/codeigniter-translatable

Example Usage:
PHP Code:
use App\Models\ArticleModel;

$articleModel model(ArticleModel::class);

// Retrieve translations
$article $articleModel->find(1);
echo 
$article->author;
// Default locale translation
echo $article->translate()->title;

// Add a new translation
$article->translate('fr')->title 'Titre en Français';

// Save changes
$articleModel->save($article); 

Docs:
https://michalsn.github.io/codeigniter-translatable/

Nested Model Relations for CodeIgniter 4

$
0
0
This library simplifies managing model relationships (e.g., parent-child or related entities) in CodeIgniter 4. It extends the base model functionality, making it easier to define and work with nested relations. It supports eager and lazy loading.

GitHub Repository: codeigniter-nested-model

Installation:
Code:
composer require michalsn/codeigniter-nested-model

Example Usage:
Initialize nad define relations.
PHP Code:
class PostModel extends Model
{
    use HasRelations;

    // ...

    protected function initialize()
    {
        $this->initRelations();
    }

    public function author(): Relation
    
{
        return $this->hasOne(UserModel::class);
    }

Use in action:
PHP Code:
use App\Models\PostModel;

$postModel model(PostModel::class);

// Retrieve a post with its author relation
$post $postModel->with('author')->find(1);

// Access the related author data
echo $post->author->name

The best part is that it uses the same models you normally create, so you can take full advantage of this fact.

Docs:
https://michalsn.github.io/codeigniter-nested-model/

transBegin problem

$
0
0
Hi
I don't know what I'm doing wrong. Without the transaction, the code works correctly. With the transaction, there is an error.   pg_affected_rows(): Argument #1 ($result) must be of type PgSql\Result, bool given
[url=https://www.duckduckgo.com/?q=TypeError+pg_affected_rows%28%29%3A+Argument+%231+%28%24result%29+must+be+of+type+PgSql%5CResult%2C+bool+given][/url]
Code:
public function test2()
{
    $db = \Config\Database::connect();
    $toInsert[] = [
        'name' => 'aaaa'
    ];
    $toInsert[] = [
        'name' => null
    ];
    try {
        $db->transBegin();
        $query = $this->db->table('public.test');
        if ($query->insertBatch($toInsert) === false) {
            d($db->error());
            d('Error from IF');
            $db->transRollback();
        }
        else
        {
            $db->transCommit();
        }
    } catch (DatabaseException $th) {
        d($th->getMessage());
        d('Error from TRY');
        $db->transRollback();
    }
}

name => null - artificial invocation of an incorrect SQL query.

Another issue is that if($query->insertBatch($toInsert) === false) never returns false. Or I don't know what needs to happen for this if statement to be satisfied.

CodeIgniter v4.5.7 bug fix released!

$
0
0
Hey guys! I know the last patch release was out a little 3 days ago but here we are dropping the ball again with a patch release before 2024 ends. This v4.5.7 patch fixes an error in loading namespaced helpers using the autoloader. It also fixes an issue with SQLite3 Forge where dropping columns always result to `false`. Please upgrade your applications to this latest version.
Changeloghttps://github.com/codeigniter4/CodeIgni...v4.5.7.rst
Upgrade guidehttps://github.com/codeigniter4/CodeIgni...de_457.rst

Visual Routes (and Route Groups Viewer)

$
0
0
Has anybody ever dreamt of a visual viewer that displays the hierarchy of routes nested in route groups?
I've been working on something like this (screenshot) for a while:

[Image: CodeIgniterWizard-visual-route-viewer.png]
What do you guys think?

Route wont work

$
0
0
Hi,

i try to run a simple redirection but i failed.

Code:
redirect('access_denied/index/myval');

it should rout to the controller in my base-folder "access_denied" to the funtion "index" and the values for the index-function with "myval".

routes.php
Code:
$routes->get('access_denied', '\App\Controllers\Access_denied::index'); //no result ->The route for "access_denied/index/myval" cannot be found
$routes->get('access_denied/(:any)', '\App\Controllers\Access_denied::index'); ->The route for "access_denied/index/myval" cannot be found

What i'm doing wrong?

Update
The Route: $routes->get('accessdenied/(:any)', 'Access_denied::index/$1');
dont work like it should be, i will always redirect to the shield/login page - maybe there is a problem with the settings about the shield-routes?

in the Filter Config is this:
Code:
public array $globals = [
        'before' => [
            // ...
            'session' => ['except' => ['login*', 'register', 'auth/a/*', 'logout']],
        ],
        // ...
    ];

if i comment this line out, the route seems to work. Now i ask myselt how i can change the filter.

I want that all pages avivable outside a subfolder in the controllers named "myadminarea" this folder should be only accessable for loggedin users.

Passing arguments to Prepared Statement

$
0
0
I am converting an old website to ci4 framework. the old site used flags and filters to build a prepared statement to search a products table. I found the prepared query doc, but I am having trouble passing additional arguments into the prepared function. For example if a var $flag was used to toggle whether to search on title only or full table :
Code:
        $search = $this->request->getVar("search");
        // test flag
        $flag = 1;
        $pQuery = $this->db->prepare(static function ($db) {
            $sql = "SELECT * FROM tblproducts";
            if(($flags&1)!=0){
                 $sql .=" WHERE title LIKE ?";
            } else {
                 $sql .=" WHERE CONCAT(title,mfrdesc,catnum,categoryname,mfrname) LIKE ?";
            }
            return (new Query($db))->setQuery($sql);
        });
        $result = $pQuery->execute($search);

How can I pass the $flag variable into the prepared statement? 

I've tried:
Code:
$search = $this->request->getVar("search");
// test flag
$flag = 1;
$pQuery = $this->db->prepare(static function ($db,$flag) {
    $sql = "SELECT * FROM tblproducts";
    if(($flags&1)!=0){
        $sql .=" WHERE title LIKE ?";
    } else {
        $sql .=" WHERE CONCAT(title,mfrdesc,catnum,categoryname,mfrname) LIKE ?";
    }
    return (new Query($db))->setQuery($sql);
});
$result = $pQuery->execute($search);
but that causes "Too few arguments to function App\\Controllers\\ApiController::App\\Controllers\\{closure}()..." error

I've also tried 
Code:
$search = $this->request->getVar("search");
// test flag
$flag = 1;
$pQuery = $this->db->prepare(static function ($db) {
    $sql = "SELECT * FROM tblproducts";
    if(($flags&1)!=0){
        $sql .=" WHERE title LIKE ?";
    } else {
        $sql .=" WHERE CONCAT(title,mfrdesc,catnum,categoryname,mfrname) LIKE ?";
    }
    return (new Query($db))->setQuery($sql);
},["flag"=>$flag]);
$result = $pQuery->execute($search);

but that does not pass the $flag into the static function.

 There are additional filters and flags that need to be implement, so it would be great if I could create the SQL statement and pass it into the prepared function.


Any help would be greatly appreciated.
~Pardner
Viewing all 14343 articles
Browse latest View live


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