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

Getting DB data as correct PHP types directly

$
0
0
Hi. Is it possible to get data from database as correct PHP types directly without retyping them?

For example:
TINYINT, INT, BIGINT as integer
FLOAT, DOUBLE, DECIMAL as float
CHAR, VARCHAR, TEXT as string

I do not care about dates as date type. Now everything, except of null, are strings. I am using MySQL database.

How to load config options into library from model. in Ci4.5

$
0
0
I have this from ci2.2 I want to know how I can do this in CI4.5
PHP Code:
        $config = array(
            
'Sandbox' => FALSE
            
'APIUsername' => $pp_username,
            
'APIPassword' => $pp_password
            
'APISignature' => $pp_signature
            
'APISubject' => '',     
            
'APIVersion' => $this->config->item('APIVersion')
        );
        
$this->load->library('paypal/Paypal_pro'$config); 

Thanks

Making 'DirectoryHasher' more re-usable

$
0
0
A little background, I was poking around with some Sass / JS minifier libraries implemented with PHP, rather than node/npm, and they seem to work quite well, easy enough to write CI4 command to get it building.
I'd now like to add an option for "watch for file changes"
I was looking at how Toolbar hot reloader works and CI already has done all the hard work and built DirectoryHasher.
The only problem is the Hasher is hard-coded to get observed directory list directly from the toolbar config file.

Looks like it wouldn't be too hard to either add a method to take in array of folders to watch, or take it in as part of the construct method, and inject the configuration array from HotReloader class, where Hasher is initiated.

That way the DirectoryHasher becomes re-usable for any other use cases, straight out of the box.

Would that be worth considering as a PR or change request?

Unsetting URI segments in CI instance

$
0
0
I'm a contractor working on upgrading a client's application from CI1 to CI4 (4.4.4 to be precise). There is a function in the legacy code that gets a value from a URI segment and then unsets that segment so that it doesn't interfere with routing. I've looked at the HTTP URI class and segments is now a protected property (and will be private in the future) so accessing the segments property directly as this code does isn't going to continue to work. I can use getSegments for that portion of the code, but I don't know how to handle the unsetting of segments as they do in that last if statement. Is there a way to unset segments in the CI instance? Should this be handled some other way?

In the legacy code this function is in a helper which is only ever accessed from a pre-controller hook. In the new code, I'll be moving this function to a filter.

Code:
function getActiveCredential() {
        $CI =& get_instance();

        // Grab the last segment of the URL
        $lastSegment = count($CI->uri->segments);
        $activeCredential = $lastSegment > 0 ? $CI->uri->segments[$lastSegment] : null;
        $activeCredential = is_numeric($activeCredential) ? $activeCredential : null;

        // Now unset it, so it doesn't affect the controllers
        if ($lastSegment > 0 && is_numeric($activeCredential)) {
            unset($CI->uri->segments[$lastSegment]);
            unset($CI->uri->rsegments[$lastSegment]);
        }

        return $activeCredential;
    }

Problem "LOAD DATA LOCAL INFILE is forbidden"

$
0
0
Hi there!
I'd like to import data from a csv file into a mysql database.
To do so I run a sql like "LOAD DATA LOCAL INFILE 'xyz.csv' INTO TABLE `abc`"
but then getting the error "LOAD DATA LOCAL INFILE is forbidden, check related settings like mysqli.allow_local_infile|mysqli.local_infile_directory or PDO::MYSQL_ATTR_LOCAL_INFILE|PDO::MYSQL_ATTR_LOCAL_INFILE_DIRECTORY".
Before working with CI I created the database connections with
$attributes = [PDO::MYSQL_ATTR_LOCAL_INFILE => true];
$connection = new PDO('mysql:host=' . $host, $username, $password, $attributes);
but I cannot find a way to do something like that in CI. Can someone give me a clue how to set this option during setting the connection?

Error / Running Codeigniter Queue

$
0
0
Hi
I Created a job class Email as in the documentation
and tried running queue using this command

Code:
php spark queue:work emails

then i got this error:

Code:
CodeIgniter v4.5.1 Command Line Tool - Server Time: 2024-06-01 04:31:19 UTC+00:00

Listening for the jobs with the queue: emails

Starting a new job: email, with ID: 11
It took: 0.0004 sec

[Error]
Call to undefined method Config\Email::getTries()
at VENDORPATH\codeigniter4\queue\src\Commands\QueueWork.php:251

Backtrace:
1 VENDORPATH\codeigniter4\queue\src\Commands\QueueWork.php:175
CodeIgniter\Queue\Commands\QueueWork()->handleWork(Object(CodeIgniter\Queue\Entities\QueueJob), Object(Config\Queue), null, null)

2 SYSTEMPATH\CLI\Commands.php:70
CodeIgniter\Queue\Commands\QueueWork()->run([])

3 SYSTEMPATH\CLI\Console.php:48
CodeIgniter\CLI\Commands()->run('queue:work', [...])

4 SYSTEMPATH\Boot.php:338
CodeIgniter\CLI\Console()->run()

5 SYSTEMPATH\Boot.php:104
CodeIgniter\Boot::runCommand(Object(CodeIgniter\CLI\Console))

6 ROOTPATH\spark:84
CodeIgniter\Boot::bootSpark(Object(Config\Paths))

what's wrong?

Error: Class "Websocket\Client" not found

$
0
0
I feel like this should not be so difficult, but I'm struggling with it for almost the entire day, so I'm asking for help!

I installed a websocket client with composer like this: 
Code:
composer require textalk/websocket


I use IntelliJ, and when I add
PHP Code:
use Websocket\Client
 and then initiate a connection with
PHP Code:
$wsClient = new Client($URL);  
there are no IDE errors indicated regarding any missing dependencies.  However, when I run the code, I get an error Class "Websocket\Client" not found.  

I have located all of the needed files in vendor/textalk folder, checked all autoload files exist, but I just don't know where to go from here. 
Thanks in advance!!!

50+ Free Bootstrap 5 Admin Dashboard Templates 2024.


Debug view comments break dynamic css

$
0
0
Hi everyone, i'm trying to use php to set dynamic variables in css, for context i'll explain better:
- The controller passes variable to view(taken with queries from database)
- The view echoes a .php file(with the variable from controller) that contains some php code and css
When debug is active every echoed view is surrounded by an html comment with debug view informations that breaks css.
I already tried with debug disabled from config and it works, so it's not my code fault but i'd like to keep debug toolbar on because i find it useful.
So here's my question: does anyone know a way or a function that echoes a view without debug comments while debug is active?
If you're reading this, thank you for your time and sorry if my english is not perfect.

str_replace(): Argument #3 ($subject) must be of type array|string, int given

$
0
0
Hi everyone,
im using number helper and implement number_to_amount() method then i faced data type error as follows:

[Image: xyASCX.jpg] 

when I try to give number with string data type this method works normally,
 
PHP Code:
number_to_amount($model->countAll(), 2'id'); // error: ($subject) must be of type array|string, int given
number_to_amount('123'2'id'); // run normally 

in previous version 4.4.8 there was no such problem.

Call to a member function getResultArray() on false

$
0
0
Hi @kenjis,
I used the MySQL and PostgreSQL database drivers to test the exact same query.

When running with MySQL there is no error issue, but when using PostgreSQL I get an error like the following:

[Image: S25iRX.jpg]

I'm currently using Codeigniter 4.5.1, on the previous version 4.4.8 that I used before there was no such error like that.
Thanks for advance.

Using typed variables in a cell view

$
0
0
Hi there!
At the moment you cannot use typed variables in cells (unless you initialize them) because they rely on get_object_vars() PHP function, which, as stated here, ignored such values.
Would it be possible to replace get_object_vars with the Reflection API so such values can be considered?
Source

Try Catch exception on MS SQL database transactions

$
0
0
Working off of this section of the documents:
https://codeigniter.com/user_guide/datab...exceptions

In a try catch, it should catch the error and bubble it up to the calling function.  We have this code:

Model:
PHP Code:
public function insertWithException(array $data)
    {
        $insert_result false;

        $db_config_obj config('Database');
        $db_config = (array) $db_config_obj;

        // DBDebug in the Database Config must be true.
        if($db_config[$this->DBGroup]['DBDebug'])
        {
            // Retrieve the builder
            $builder $this->builder();

            // Remove the unnecessary fields from the entity,
            // using the allowFields array
            $cleaned_data $this->doProtectFields($data);

            $builder->set($cleaned_data);
            $sql $builder->getCompiledInsert();

            try
            {
                $this->db->transException(true);
                $this->db->transStart();
                $this->db->query($sql);
                $this->db->transComplete();
            }
            catch (\Exception $e)
            {
                // Automatically rolled back already.
                // Pass the exception up to the controller
                throw $e;
            }
        }
        return $insert_result;
    

And this calling function:
PHP Code:
try
        {
            $fM->insertWithException($firedrillEntity->toArray());
        }
        catch (\Exception $e)
        {
            echo "Insert failed. <br>";
            echo "Error: " $e->getMessage(); // Display the error message
        

However, the code failed on the $this->db->query($sql); line when it should have bubbled up.

Our fix is this:

Model:
PHP Code:
try
            {
                $this->db->transException(true);
                $this->db->transStart();
                $this->db->query($sql);
                $this->db->transComplete();
            }
            catch (\Throwable $e)
            {
                // Automatically rolled back already.
                // Pass the exception up to the controller
                throw $e;
            

Calling function:
PHP Code:
try
        {
            $fM->insertWithException($firedrillEntity->toArray());
        }
        catch (\Exception $e)
        {
            echo "Insert failed. <br>";
            echo "Error: " $e->getMessage(); // Display the error message
        }
        catch (\Throwable $e)
        {
            echo "Insert failed. <br>";
            echo "Error: " $e->getMessage(); // Display the error message for other types of errors
        

This works, so we're happy with it, however, is there something we missed that would have worked per the documentation?

Speed Up Your Site with 3 Simple JavaScript Performance Optimization Tips

Turn off CI4 Session handling in v4.5.1 ?

$
0
0
Hello,
CI project was on v4.3, recently upgraded to v4.5.1.

Now Session settings are in new config file Session.php, it does not appear to be possible to turn off CI Session handling. In my BaseController, a session is created (outside of CI4), and the error below appears, because my session has indeed already been started.

There appears to be nothing in CI docs about disabling CI Session handling. Is it possible to disable now?

TIA
Mike

PHP: 8.2.19 — CodeIgniter: 4.5.1 -- Environment: development

Code:
ErrorException
ini_set(): Session ini settings cannot be changed when a session is active
SYSTEMPATH/Session/Handlers/FileHandler.php at line 74

Code:
67
68     public function __construct(SessionConfig $config, string $ipAddress)
69     {
70         parent::__construct($config, $ipAddress);
71
72         if (! empty($this->savePath)) {
73             $this->savePath = rtrim($this->savePath, '/\\');
74             ini_set('session.save_path', $this->savePath);
75         } else {
76             $sessionPath = rtrim(ini_get('session.save_path'), '/\\');
77
78             if ($sessionPath === '') {
79                 $sessionPath = WRITEPATH . 'session';
80             }

Any user guid or video on CI4-Interiajs

$
0
0
Hi,
I read all about InertiaJs and integrating with Laravel (not a fan). I also realized from the documentation that there is an adapter for CI4 in GitHub. Problem is I do not know where to find a user guide or video tutorial on how to use Inertiajs with CI4.
Appreciate any help. Thank you

array_column does not work with Entity

$
0
0
Hi everyone,
I have code like this:

PHP Code:
$notifications model(NotificationSettingModel::class)->withScheduleNotification()->find($userIds);

    if (empty($notifications)) {
         return false;
    }

$users model(UserModel::class)->find(array_column($notifications'user_id')); 


after running it, i got an error like this:
 
Code:
array_column(): Argument #1 ($array) must be of type array, App\Entities\NotificationSetting given


even though in version 4.4.8 the code above runs fine. but why doesn't it work on version 4.5.1?

i took an example from this repositori: 
https://github.com/lonnieezell/forum-exa...t.php#L121

Thanks All.

The version 4.5.0 cause problems with loading dotEnv

$
0
0
Hello,
I develop applications whose code is shared by multiple instances on the same platform (multiple URLs, with separate parameters for each). To do that, I've modified the index.php
code with:
Code:
if (is_file($file = $_SERVER["envPath"] . DIRECTORY_SEPARATOR . ".env") && is_readable($file)) {
    (new CodeIgniter\Config\DotEnv($_SERVER["envPath"],".env"))->load();
The envPath variable is assigned in apache2 vhost, each instance has its own vhost file.
But in the last version (4.5.0), this code as migrated to the core of CodeIgniter. If I can change the Boot.php file to insert it, a
Code:
composer upgrade
will overwrite it.
Have you a solution to avoid this overwrite?
Thanks,
Eric Q.

REST API Design Rules

17 Killer Tools & Web Apps to Boost Your Productivity in 2024

Viewing all 14348 articles
Browse latest View live


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