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

Missing Model

$
0
0
hi, i just try to make attandance app for my school library but my app cant find my model when i call it in controler.

here is my controler

Code:
<?php

namespace App\Controllers;

use app\Models\AbsenModel;
use app\Models\SiswaModel;

class absen extends BaseController
{
    protected $absenmodel;
    protected $siswamodel;

    public function __construct()
    {
        $this->absenmodel = new AbsenModel();
        $this->siswamodel = new SiswaModel();
    }

    public function index(): string
    {
        return view('perpus/Dashboard.php');
    }

    public function save()
    {
        $ids = $this->request->getvar('ids');
        $date = now();
        $nama = $this->siswamodel->getnama($ids);
        $kelas = $this->siswamodel->getkelas($ids);
        $this->absenmodel->save([
            'idsiswa' => $ids,
            'nama' => $nama,
            'kelas' => $kelas,
            'date' => $date
        ]);
        return redirect()->to('/Absensi');
    }

    public function absensi()
    {
        $data =
            [
                'absen' => $this->absenmodel->getuser()
            ];
        return view('perpus/viewabsen', $data);
    }
}

and this is my model

Code:
<?php

namespace App\Models;

use CodeIgniter\Model;

class AbsenModel extends Model
{
    protected $table = 'absen';
    protected $useTimestamps = true;
    protected $allowedFields = ['idsiswa', 'nama', 'kelas', 'date'];

    public function getuser($id = false)
    {
        if ($id == false) {
            return $this->findAll();
        }
        return $this->where(['id' => $id])->nama();
    }
}

Codeigniter giving 503 service unavailable

$
0
0
Hello,
I get this error when fetching heavy data. Why? Huh

PHP Benchmarks (Codeigniter)

$
0
0
Excellent Read (updated Mar. 2024): PHP Benchmarks: Speed Tests for Versions 8.1, 8.2, and 8.3 (kinsta.com)


Quote from article... 
Quote:CodeIgniter, in its default installation, is fast — very fast. PHP benchmark results for 8.1 and 8.2 were similar, with 8.2 slightly quicker than 8.1. PHP 8.3 comes in full force with a 42% performance increase, making the upgrade another no-brainer.

Why PHP is Gaining Popularity in 2024: The Unexpected Comeback of a Classic Language

Try catch is not working

$
0
0
Im trying to catch errors when data is not inserted on the database.
This is may code:
try {
$id = (new CatalogModel)->create([
'role' => post('role'),
'title' => post('title'),
]);
model('App\Models\ActivityLogModel')->add('Se ha creado un nuevo grupo: '.$id.' Creado por: '.logged('name'), logged('id'));
} catch (\Exception $e) {
model('App\Models\ActivityLogModel')->add('Error al crear grupos:'. $e->errorMessage(), logged('id'));
}

But its not working and allways redirect to error page (errors/html/production.php).

Any help on this?

Combining multiple queries to get the result

$
0
0
Hi,
I want to do some calculations but no success , how to convert this in simple and working query, most important variable is $sale_cost. What I would like to achieve is $sale_cost, I am also selecting $sale_cost in another query

Is there any shortcut to do all calculation in few working queries

Any help is very appreciated

Release of SMS Rocket Package for CodeIgniter 4

$
0
0
Hello to all the dear users of the CodeIgniter 4 community!  Smile

I am excited to announce the release of a new package called sms-rocket for CodeIgniter 4. This package is designed to address common challenges in integrating SMS services and offers the following features:

Multi-driver support: Easily switch between different SMS providers.
Caching: Caches SMS responses to reduce redundant requests.
Logging: Logs SMS sending operations for easy debugging and monitoring.
Retry Mechanism: Automatically retries failed message sending attempts.
Multiple Messaging: Supports sending SMS to multiple recipients at once.
User Integration: Automatically detects the phone number field from User models (integration with CodeIgniter Shield).
Data History: Maintains a complete history of SMS transactions in the database for future reference and analysis.
Sensitive Data Handling: Provides functionality to obfuscate sensitive information before storing it in the database to enhance security and privacy.

PHP Code:
/** @var SMSRocketService $smsService */
$smsService service('smsRocket');
$twilio $smsService->driver('twilio')
        ->setSender('+120XXXXXX')
        ->setReceiver('+9809118840000')
        ->setMessage('Ticket #20 has been created.')
        ->send();
if(
$twilio->isOK()){
    echo "Your SMS request has been successfully sent to the Twilio provider. {$twilio->getMessageId()}";    


I invite you to try out this package and share your feedback with me. Together, we can grow the CodeIgniter community and create better projects!
If you wish, you can submit a pull request for the driver related to your favorite provider to enhance the package.

docs : https://www.smsrocket.codeigniter4.ir/
github: https://github.com/datamweb/sms-rocket

Behaviour of getInsertID() when using save()

$
0
0
When using the CI Model for basic CRUD, does `getInsertID()` return null when a preceding `save()` did an UPDATE rather than INSERT? Or does it return the affected primary key regardless? This detail would be a great addition to that method's documentation entry.

Nesting level too deep - recursive dependency?

$
0
0
Hi all,
For a project, I wrote a specific method that accepts posted data (via a javascript - by means of axios). 
The method is written to handle (ajax) file uploads and save file details in a database table. Since there are multiple file uploads in the, I tried to handle them all via this one method (below).
Following vars are send as formData:
  • (file upload) label : to handle validtaion errors 
  • file input name : corresponding a field in the database
  • type : there are 3 form types, so all starting with a different 3 letter code, followed by '_requests' (corresponding the model; e.g. 'con_requests')
  • id : the id of the record in the corresponding table (type, if form type is 'con', it will be the 'con_table', edited by means of the  'con_requests' model)
In the method below, the save($entity) action throws the 'Nesting level too deep - recursive dependency?' error. The weird thing is that some file uploads work perfect and are perfectly stored in the db table, where as others fail and throw this error. 
I can echo out the changed entity property, entity looks OK, even the hasChanged() method return TRUE... 
I don't have a clue how to fix it...  Huh

PHP Code:
public function axUpload()
    {
        $posted $this->request->getPost();
        
        
if(!array_key_exists("label"$posted) || !array_key_exists("file_input"$posted))
        {
            $data = [ 'success' => 'false''text' => 'No label or file input fieldname provided!' ];
            $res array_merge($data , ['statusText' => 'OK''request' => $posted]);
            return $this->respond($res);
        }

        $label $posted['label'];
        $filefield $posted['file_input'];
        $type $posted['type'];
        $id $posted['id'];

        $file $this->request->getFile($filefield); // CI File Object

        $rules = [
            $filefield => [
                'label' => $label,
                'rules' => [ 'uploaded['.$filefield.']''mime_in['.$filefield.',application/pdf]''max_size['.$filefield.',1500000]', ],
                'errors' => [ 'uploaded' => 'File was not uploaded''mime_in' => 'Only PDF files are allowed''max_size' => 'The uploaded file is too big', ]
            ],
        ];

        $validation service('validation');
        $validation->setRules($rules);


        if(! $this->validateData([$file], $rules))
        {
            $errors $validation->getErrors();
            $data = [ 'success' => 'false''errors' => $errors'mime' => $file->getMimeType(), 'size' => $file->getSize() ];

            $res array_merge($data , ['statusText' => 'OK''request' => $posted]);
            return $this->respond($res);
        }
        else
        {
            $fileExt $file->getClientExtension();
            $newName $this->user->initials '_' date('Ymd_His') . '__' strtolower($filefield) . '.' strtolower($fileExt);
            $path 'uploads/fcwo/'.$this->user->initials.'/'.date('Ymd').'/';

            // Move file to location and keep track of upload in DB
            if ($file->isValid() && !$file->hasMoved())
            {
                $file->move(WRITEPATH.$path$newName);
                $data = [ 'success' => 'true''filename' => $newName'path' => $path.$newName'size' => $file->getSize() ] ;

                // Save file info in DB, which table / type?
                $model $this->_createModelInstance($type); // creates corresponding model instance, if type = 'con', it returns the con_requests model
                $entity $model->find($id);

                unset($entity->$filefield);
                $entity->$filefield =  json_encode(['filename' => $newName'path' => $path.$newName]); // all ok until here!

                if ($entity->hasChanged()) // returns true
                {
                    if($model->save($entity)) 
                    
{
    /* And here, the script stops ...

    "Nesting level too deep - recursive dependency?
    Previous Exception
    CodeIgniter\\Database\\Exceptions\\DataException
    There is no data to update.
    #0 /earthweb2_ci4/CodeIgniter/system/BaseModel.php(1011): CodeIgniter\\Database\\Exceptions\\DataException::forEmptyDataset('update')
    #1 /earthweb2_ci4/CodeIgniter/system/Model.php(865): CodeIgniter\\BaseModel->update(Array, Array)
    #2 /earthweb2_ci4/CodeIgniter/system/BaseModel.php(749): CodeIgniter\\Model->update('6', Object(Modules\\Fcwo\\Entities\\ConEntity))
    #3 /earthweb2_ci4/CodeIgniter/modules/Fcwo/Controllers/Fcwo.php(249): CodeIgniter\\BaseModel->save(Object(Modules\\Fcwo\\Entities\\ConEntity))
    #4 /earthweb2_ci4/CodeIgniter/system/CodeIgniter.php(933): Modules\\Fcwo\\Controllers\\Fcwo->axUpload()
    #5 /earthweb2_ci4/CodeIgniter/system/CodeIgniter.php(509): CodeIgniter\\CodeIgniter->runController(Object(Modules\\Fcwo\\Controllers\\Fcwo))
    #6 /earthweb2_ci4/CodeIgniter/system/CodeIgniter.php(355): CodeIgniter\\CodeIgniter->handleRequest(NULL, Object(Config\\Cache), false)
    #7 /earthweb2_ci4/CodeIgniter/system/Boot.php(325): CodeIgniter\\CodeIgniter->run()
    #8 /earthweb2_ci4/CodeIgniter/system/Boot.php(67): CodeIgniter\\Boot::runCodeIgniter(Object(CodeIgniter\\CodeIgniter))
    #9 /earthweb2_ci4/WWW/index.php(56): CodeIgniter\\Boot::bootWeb(Object(Config\\Paths))\n#10 {main}",

        "file": "/earthweb2_ci4/CodeIgniter/system/Debug/Exceptions.php",
        "line": 602,
    */
                        return $this->respond($data);
                    }
                    else
                    {
                        // Info not saved in DB, remove uploaded file!
                        if(file_exists(WRITEPATH.$path.$newName))
                        {
                            unlink(WRITEPATH.$path.$newName);
                        }
                        $data = [ 'success' => 'false''errors' => [$filefield => 'Record could not be updated, try again''path' => $path.$newName] ] ;
                    }
                }
                die("Nothing has changed!");
            }

            $data = [ 'success' => 'false''errors' => [$filefield => 'File upload failed, invalid file or failed to move to uploads''path' => $path.$newName] ] ;
        }

        $res array_merge($data , ['statusText' => 'OK''request' => $posted]);

        return $this->respond($res);
    

Thanks in advance for your help!

Zeff

"Build your first application" tutorial

$
0
0
Hi

I am starting to learn CodeIgniter and am working my way through the "Build your first application" tutorial on the official site. Some things are not working correctly (eg. "Add the following lines, after the route directive for ‘/’: with no explanation of what route directive means).

Rather than ask questions here every time there is a problem, is it possible to download the pages for the completed app as it should be so that I can compare my code with the working version? It would be easier for newcomers.
Thanks

Access request and response in boot

$
0
0
Hello,
I want to access request and responses objects during boot sequence, in app\Config\Boot\development.php (and production).
I have try $request=Services::request(), $request = \Config\Services::request(), ... Nothing.
Before upgrade it's work (4.3.3) and now, not (4.5.5)...
Thanks

"No: 'noindex' detected in 'robots' meta tag" for coedigniter site

$
0
0
When attempting to index the Codeingniter website using Google Search Console, it reports "No: 'noindex' detected in 'robots' meta tag". Please help address this issue.

redirect( 'xxx' ) not working properly

$
0
0
Hi,
I have upgraded from CI 4.0.3 to the latest version. Working through the required changes to my code, all seems clear, except this issue. At one place the code uses a redirect( 'login' ) function. This results in an attempt to navigate to https://login/login. After some investigation i was able to determine the reason, not sure what's causing it though. Any help appreciated.
Here is the call stack at the moment things go wrong:
PHP Code:
/Users/JanZ/Sites/nexus2/system/HTTP/SiteURI.php.CodeIgniter\HTTP\SiteURI->determineBaseURL(): lineno 147 
/Users/JanZ/Sites/nexus2/system/HTTP/SiteURI.php.CodeIgniter\HTTP\SiteURI->__construct(): lineno 102 
/Users/JanZ/Sites/nexus2/system/HTTP/SiteURI.php.CodeIgniter\HTTP\SiteURI->siteUrl(): lineno 428 
/Users/JanZ/Sites/nexus2/system/Helpers/url_helper.php.site_url(): lineno 39 
/Users/JanZ/Sites/nexus2/system/HTTP/RedirectResponse.php.CodeIgniter\HTTP\RedirectResponse->route(): lineno 67 
/Users/JanZ/Sites/nexus2/system/Common.php.redirect(): lineno 853 
/Users/JanZ/Sites/nexus2/app/ThirdParty/myth-auth/Filters/LoginFilter.php.Myth\Auth\Filters\LoginFilter->before(): lineno 74 
/Users/JanZ/Sites/nexus2/system/Filters/Filters.php.CodeIgniter\Filters\Filters->runBefore(): lineno 203 
/Users/JanZ/Sites/nexus2/system/Filters/Filters.php.CodeIgniter\Filters\Filters->run(): lineno 184 
/Users/JanZ/Sites/nexus2/system/CodeIgniter.php.CodeIgniter\CodeIgniter->handleRequest(): lineno 481 
/Users/JanZ/Sites/nexus2/system/CodeIgniter.php.CodeIgniter\CodeIgniter->run(): lineno 355 
/Users/JanZ/Sites/nexus2/system/Boot.php.CodeIgniter\Boot::runCodeIgniter(): lineno 325 
/Users/JanZ/Sites/nexus2/system/Boot.php.CodeIgniter\Boot::bootWeb(): lineno 67 
/Users/JanZ/Sites/nexus2/public/index.php.{main}(): lineno 56 
The site_url function (url_helper.php, line 33) calls the service( 'request' )->getURI() function and the resulting object has the property $host set to "". So when the code gets to SiteURI->determineBasseURL, the $host parameter is not NULL but has a value of "" instead. As a result, even though the created $uri object has the correct value for the $host property, this code starting on line 159 clears it out:
PHP Code:
        if ($host !== null) {
            $uri->setHost($host);
        

It seems like an additional check for $host being an empty string is the solution, but there is still a high probability I have something somewhere configured wrong. Any help would be greatly appreciated.
Thanks!

dompdf pahe numbering for html exceeding one print page.

$
0
0
Hi everyone.
i fetched some html content from phpmyadmin sql table and print them to pdf by dompdf in my codeigniter 3 project.
here, i have some columns (page titles) with some html content which could be exceeds one print page (A4 landscape).
as well i add page number or background cover for pages, but just the first page in each column content has cover image and just the last page has footers for page number.
here is the function i used to create html content for dompdf:
PHP Code:
    // Helper function to generate page HTML with title
    public function generatePageHtml($name,$title1$title2 null$title3 null$content$image_path$page_number=null) {
        $html '<div style="position: relative; width: 100%; height: 100%; page-break-after: always; margin: 0; padding: 0;">';
        $html .= '<style>@page { margin: 0; }</style>';
    
        
if ($image_path && file_exists($image_path)) {
            $image file_get_contents($image_path);
            $base64 'data:image/jpeg;base64,' base64_encode($image);
            $html .= '<img src="' $base64 '" style="position: absolute; top: 0; left: 0; width: 100%; height: 100%; z-index: -1; object-fit: cover; margin: 0; padding: 0;">'// opacity: 0.7;
        }
    
        $html 
.= '<div style="padding: 20px; position: relative; z-index: 1; margin: 0;">';
        $html .= '<h1 style="text-align: center; text-decoration: underline; margin: 0;">' $title1 '</h1>';
    
        
if ($title2) {
            $html .= '<h2 style="text-align: center; margin: 0;">' $title2 '</h2>';
        }
        if ($title3) {
            $html .= '<h3 style="text-align: center; margin: 0;">' $title3 '</h3>';
        }
    
        $html 
.= $content;
        $html .= '</div>';
        $html .= '<div style="position: absolute; bottom: 20px; left: 20px; font-size: 12px; font-weight: bold;font-style: italic; color: gray;"> '$name .' - '$title1' - '$title2'</div>';

        if ($page_number !== null) {
            $html .= '<div style="position: absolute; bottom: 20px; right: 10px; font-size: 12px; font-weight: bold; color: gray;border: 1px solid black; padding: 10px; display: inline-block; border-radius: 3px;"> '.$page_number '</div>';
        }
        $html .= '</div>';
        return $html;
    

how should i consider coding so that when a html content exceeds one print page, the next pages of same content as well has cover image and get numbering as well.

How to Store API Keys Securely in a .env File


CodeIgniter not working on localhost

$
0
0
Hello,
I have a problem. It is that CodeIgniter doesn't seem to work on localhost.

Base URL in config.php:

Code:
$config['base_url'] = 'http://sample_localhost/mysite/';

Settings in database.php:


Code:
$db['default']['hostname'] = 'sample_localhost';
$db['default']['username'] = 'root';
$db['default']['password'] = 'admin';
$db['default']['database'] = 'my_database';

Any help is very much appreciated. Thanks in advance!

env = development but no debug toolbar

$
0
0
Hello
I've installed, changed the env to .env, uncommented CI_ENVIRONMENT and set it to development, but I don't get the debug toolbar.  The "Build Your First Application" page says:

Debug Toolbar

Now that you’re in development mode, you’ll see the CodeIgniter flame on the right bottom of your application. Click it and you’ll see the debug toolbar.


But I dont get a flame.  Image of what I get is below:

[Image: smpz326.png]

I've used Edge, Firefox, and Chrome.  What am I missing?

How to use CLI generator

$
0
0
I want to create restful controller.

How to use a namespace in CLI for App\Controllers\Api

app/Controllers/Api/FooController.php

Tried this command and failed.
php spark make:controller Foo --namespace --restful --suffix


Please help. Thank you

Migration issue SQL Server

$
0
0
I'm using SQL Server and using schema name instead of dbo.

north.userTable

Somehow $this->forge->addForeignKey('user_id', 'userTable', 'id', '', 'CASCADE') does not add schema in table userTable and show error.


Please help.

Thank you.

Shield setup issue

$
0
0
I'm planning to use shield for user management

I'm aware that this add-on will also include settings library.

I don't want to use database handler for settings and want to use array instead. For this, I need to change the handler by extending the settings config manually.

Suggestions:
Extend the Settings config for app/Config same as Auth, AuthGroups, AuthTokens. Only Run the migrations if the handler is set to database.


Thank you.
Viewing all 14343 articles
Browse latest View live


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