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

ERROR: Failed to get field data from Database

$
0
0
I'm creating a surveys manager feature for my website. It can create a survey, edit, and delete. It's fine for the create, but not for the edit. When I'm trying to edit the "pertanyaan" (meaning: question) and added new questions that's not exist in the database, it throws an error like this:
ERROR: Failed to get field data from database.

That's somehow, it's caused by the update batch from the edit function I created.

For more information, the things that I've inspect are:
1. The columns whether on the website or the database are already good.
2. The HTML for loading the data is also good.
3. The data sent is also correct.

Here's the full code of edit function:
PHP Code:
function editPertanyaanData($database$data)
{
  $builder $database->table('s_pertanyaan');
  $idSurvey $data['id_survey'] ?: null;
  $idPertanyaan $data['id_pertanyaan'] ?: null;
  $pertanyaan $data['pertanyaan'] ?: null;
  $jenis $data['jenis'] ?: null;
  if (!$idSurvey || !$idPertanyaan || !$pertanyaan || !$jenis) {
    return null;
  }
  if (!empty($idPertanyaan)) {
    $builder->where('id_survey'$idSurvey)
      ->whereNotIn('id'$idPertanyaan)
      ->delete();
  }
  $pertanyaanDataUpdate = [];
  $pertanyaanDataInsert = [];
  foreach ($pertanyaan as $index => $teks) {
    $jenisValue = isset($jenis[$index]) && is_numeric($jenis[$index]) ? (int) $jenis[$index] : 1;
    if (empty($idPertanyaan[$index])) {
      $pertanyaanDataInsert[] = [
        'id_survey' => $idSurvey,
        'teks' => $teks,
        'jenis' => $jenisValue,
        'is_aktif' => true,
        'urutan' => $index 1,
        'created_at' => date('Y-m-d H:i:s'),
        'updated_at' => date('Y-m-d H:i:s'),
      ];
      continue;
    }
    $pertanyaanDataUpdate[] = [
      'id' => $idPertanyaan[$index],
      'id_survey' => $idSurvey,
      'teks' => $teks,
      'jenis' => $jenisValue,
      'is_aktif' => true,
      'urutan' => $index 1,
      'updated_at' => date('Y-m-d H:i:s'),
    ];
  }
  if (!empty($pertanyaanDataUpdate)) {
    $builder->updateBatch($pertanyaanDataUpdate, ['id']);
  }
  if (!empty($pertanyaanDataInsert)) {
    $builder->insertBatch($pertanyaanDataInsert);
  }
  return $database->affectedRows() > 0;



And here's how I call it:
PHP Code:
public function editSurvey($idSurvey)
  {
    if ($this->request->getMethod() === "POST") {
      $data $this->request->getPost();
      $data['dokumen_pendukung_survey'] = $this->request->getFile('dokumen_pendukung_survey');
      $database Database::connect();
      $database->transStart();
      $data['id_survey'] = $idSurvey;
      editSurveydata($database's_survey', [
        'kode' => $data['kode_survey'],
        'nama' => $data['nama_survey'],
        'dokumen_pendukung' => $data['dokumen_pendukung_survey'],
        'status' => $data['status_survey'],
      ], $idSurvey);

      if (!$idSurvey) {
        $database->transRollback();
        $database->close();
        return;
      }
      $result editSurveydata($database's_pelaksanaan_survey', [
        'id_periode' => $data['id_periode'],
        'tanggal_mulai' => $data['tanggal_mulai'],
        'tanggal_selesai' => $data['tanggal_selesai'],
        'deskripsi' => $data['deskripsi_survey'],
        'created_at' => date('Y-m-d H:i:s'),
      ], $idSurvey);
      if (!$result) {
        $database->transRollback();
        $database->close();
        return;
      }
      $result editPertanyaanData($database$data);
      if (!$result) {
        $database->transRollback();
        $database->close();
        return;
      }
      $database->transCommit();
      $database->close();
      return alert('survey/manajemen-survey''success''Survey berhasil diupdate!');
    }

    $data['survey'] = $this->surveyModel->find($idSurvey);
    if (!$data['survey']) {
      return alert('survey/manajemen-survey''error''Survey tidak ditemukan!');
    }
    $data['pelaksanaan_survey'] = $this->pelaksanaanSurveyModel->where('id'$idSurvey)->first();
    if (!$data['pelaksanaan_survey']) {
      return alert('survey/manajemen-survey''error''Pelaksanaan survey tidak ditemukan!');
    }
    $data['periode'] = $this->periodeModel->findAll();
    $data['pertanyaan'] = $this->pertanyaanSurveyModel->where('id_survey'$idSurvey)->orderBy('urutan''asc')->findAll();
    echo view('layouts/header.php', ["title" => "Manajemen Survey"]);
    echo view('survey_kepuasan/manajemen_survey/edit_survey.php'$data);
    echo view('layouts/footer.php');
  

Using Pager with an Array

$
0
0
Hi

I have some results from a Model that needs to be cached after being parsed to clean user comments.

Is there's a way to use Pager with an Array?

Thanks

Why Every Programmer Needs a Non Computer Hobby

5 Things I Wish I Knew Before Starting a Startup as a Software Engineer

Can't create new database with forge

$
0
0
I have tried this: 
PHP Code:
$forge = \Config\Database::forge();
$forge->createDatabase('test_1002'); 


and this:

PHP Code:
$dbName 'test_1002';
$sql "CREATE DATABASE {$dbName}";
$query $this->db->query($sql); 


and I get: 

PHP Code:
CRITICAL 2025-05-06 03:35:45 --> [Caused bymysqli_sql_exceptionAccess denied for user 'development'@'%' to database 'test_1002' 


The server is Liquid Web Alma Linux, Maria DB, Plesk... the db user has full access to all functions and all databases. 
I can create a db over ssh but it doesn't show up to Plesk, because Plesk only tracks it's own databases. 
Does anyone know how to get past this, and create Plesk visible databases with CI4?

systemDirectory conundrum

$
0
0
Hi all,
Just did a test install of CI v4.6.1 with composer. All worked fine and dandy.

I noticed that in app/Config/Paths the $systemDirectory is:
PHP Code:
    public string $systemDirectory __DIR__ '/../../vendor/codeigniter4/framework/system'


I'm sure that in v4.5 (and earlier) $systemDirectory was
PHP Code:
public string $systemDirectory __DIR__ '/../../system'

and that for every install I would have to edit this to _DIR__ . '/../../vendor/codeigniter4/framework/system' in Paths.php

Was this a bug? I'm curious because I've just seen a v4.4.0 installation (not mine) with system directory at the same level as app.

Don't know why system directory would be at the same level as app. Was this for a non-composer install??

TIA
Mike

Update to 4.6.1

$
0
0
I'm updating some applications and one of the files that has changed is Config/Paths.php.
Compared to the previous one, it has a different value for the $systemDirectory variable, before it was:

PHP Code:
public string $systemDirectory __DIR__ '/../../vendor/codeigniter4/framework/system'


now instead I find:

PHP Code:
public string $systemDirectory __DIR__ '/../../system'


But this will never work, the system folder is not located there.

Am I doing something wrong?

my controller fails to find helper function

$
0
0
Hi Team,
I love the new error interface - great job!
Its helping me to upgrade my ci3 to ci 4.6.0
Latest snag is my controller which extends BaseController cannot find the validation function:
- the function is 'is_valid_level' which is defined in a Helper myvalidate_helper.php
- the myvalidate helper is loaded (I think) by adding to the $helpers array in the BaseController (I can see it in the list of files).
- ci3 call was
PHP Code:
if (!is_valid_level($level3)) { .... 
- and I changed it to after a bit of research
PHP Code:
if (!myvalidate(is_valid_level($level3))) { .... 
- and the error reported is: Call to undefined function App\Controllers\myvalidate()
Clearly I have misunderstood something important, so could someone explain what I have got wrong please?
Thx Paul

MVC vs MVCS vs CodeIgniter

$
0
0
Hi,
Reading this post Better than MVC.
What do you think? 
I saw some messages about using CI that way and makes sense to me...

Cheers.

update the framework to the latest version

$
0
0
I am in the process of updating my CodeIgniter framework from version 4.1.3 to 4.1.4. The process requires me to update incrementally, step by step for each version. I initially attempted to use the "composer update" command, however, it only updated the libraries and not the framework itself. As a result, I am searching for a solution to effectively update the framework to the latest version.

My Library cannot see session

$
0
0
Hi Team, (having resolved helper issue) the debugging show one of my libraries cannot see the session.
I have loaded the library (Template) and the session in the BaseController ie
PHP Code:
<?php

namespace App\Controllers;

use 
CodeIgniter\Controller;
use 
CodeIgniter\HTTP\CLIRequest;
use 
CodeIgniter\HTTP\IncomingRequest;
use 
CodeIgniter\HTTP\RequestInterface;
use 
CodeIgniter\HTTP\ResponseInterface;
use 
Psr\Log\LoggerInterface;

/**
* Class BaseController
*
* BaseController provides a convenient place for loading components
* and performing functions that are needed by all your controllers.
* Extend this class in any new controllers:
*    class Home extends BaseController
*
* For security be sure to declare any new methods as protected or private.
*/
abstract class BaseController extends Controller
{
    /**
    * Instance of the main Request object.
    *
    * @var CLIRequest|IncomingRequest
    */
    protected $request;

    /**
    * An array of helpers to be loaded automatically upon
    * class instantiation. These helpers will be available
    * to all other controllers that extend BaseController.
    *
    * @var list<string>
    */
    protected $helpers = ['url''form''functions''time''myvalidate''debug'];

    /**
    * Be sure to declare properties for any property fetch you initialized.
    * The creation of dynamic property is deprecated in PHP 8.2.
    */
    public $session;
public 
$db;
public 
$smail;
public 
$ajax;
public 
$template;
public 
$get;
public 
$make;
public 
$delete;

    /**
    * @return void
    */
    public function initController(RequestInterface $requestResponseInterface $responseLoggerInterface $logger)
    {
        // Do Not Edit This Line
        parent::initController($request$response$logger);

        // Preload any models, libraries, etc, here.

        $this->session = \Config\Services::session();
$this->db = \Config\Database::connect();

$this->smail = new \App\Libraries\Smail();
$this->ajax = new \App\Libraries\Ajax();
$this->template = new \App\Libraries\Template();
$this->get = new \App\Libraries\Get();
$this->make = new \App\Libraries\Make();
$this->delete = new \App\Libraries\Delete();

    }

My controller calls the Template lib which in turn tries to access the session.
I appreciate the libs do not extend BaseController, but I was hoping $this->template and $this->session would be available to everything.
I'm sorry but I appear to be in a morasse of object inheritance and am not sure what to do to fix this?
The error thrown is: Undefined property: App\Libraries\Template::$session
The code snippet from my Template lib is;
PHP Code:
public function render($name$admin false)
    {
        $ip_address real_ip();

        if (!$this->session->get('view_site') || is_ip_blocked($ip_address)) {
            return;
        
Any pointers appreciated, thx, Paul

Why PHP is still worth learning in 2025:By the numbers

Ajax post failing with TypeError

$
0
0
I have defined the route and when I actually fire the JS I end up with the following: (CI 4.6.0, on FireFox). Is this a CI problem please?
{
    "title": "TypeError",
    "type": "TypeError",
    "code": 500,
    "message": "CodeIgniter\\HTTP\\Request::fetchGlobal(): Argument #3 ($filter) must be of type ?int, true given, called in /var/www/html/gnb/ci460/system/HTTP/IncomingRequest.php on line 714",
    "file": "/var/www/html/gnb/ci460/system/HTTP/RequestTrait.php",
    "line": 258,
    "trace": [
        {
            "file": "/var/www/html/gnb/ci460/system/HTTP/IncomingRequest.php",
            "line": 714,
            "function": "fetchGlobal",
            "class": "CodeIgniter\\HTTP\\Request",
            "type": "->"
        },
        {
            "file": "/var/www/html/gnb/ci460/app/Controllers/TheBigPicture.php",
            "line": 148,
            "function": "getPost",
            "class": "CodeIgniter\\HTTP\\IncomingRequest",
            "type": "->"
        },
        {
            "file": "/var/www/html/gnb/ci460/system/CodeIgniter.php",
            "line": 933,
            "function": "interact",
            "class": "App\\Controllers\\TheBigPicture",
            "type": "->"
        },
        {
            "file": "/var/www/html/gnb/ci460/system/CodeIgniter.php",
            "line": 507,
            "function": "runController",
            "class": "CodeIgniter\\CodeIgniter",
            "type": "->"
        },
        {
            "file": "/var/www/html/gnb/ci460/system/CodeIgniter.php",
            "line": 354,
            "function": "handleRequest",
            "class": "CodeIgniter\\CodeIgniter",
            "type": "->"
        },
        {
            "file": "/var/www/html/gnb/ci460/system/Boot.php",
            "line": 334,
            "function": "run",
            "class": "CodeIgniter\\CodeIgniter",
            "type": "->"
        },
        {
            "file": "/var/www/html/gnb/ci460/system/Boot.php",
            "line": 67,
            "function": "runCodeIgniter",
            "class": "CodeIgniter\\Boot",
            "type": "::"
        },
        {
            "file": "/var/www/html/gnb/ci460/public/index.php",
            "line": 56,
            "function": "bootWeb",
            "class": "CodeIgniter\\Boot",
            "type": "::"
        }
    ]
}

CI4 Auto-Discovery not working on dedicated server (cpanel)

$
0
0
I am working on a prototype using Modules. Everything is working fine in xampp on my windows desktop. When I deploy it to my dedicated server, it cannot find the routes

Folder structure
app
     Config
         Autoload
         Routes
cits
     Blog
          Config
               Routes
          Controllers
               Blog

FILES:

app\Config\Routes
----------------------------------------------------------
service('auth')->routes($routes);
$routes->get('/', 'Home::index');


app\Config\Autoload
---------------------------------------------------------
public $psr4 = [
    APP_NAMESPACE => APPPATH,
    'Config' => APPPATH . 'Config',
    'Cits\Settings' => ROOTPATH . 'cits\Settings',
    'Cits\Blog' => ROOTPATH . 'cits\Blog',
];

\cits\Blog\Config\Routes
---------------------------------------------------------
$routes->group("blog", ["namespace" => "\Cits\Blog\Controllers"], function ($routes) {
    $routes->get("/", "Blog::index");
});
Error I receive:  Can't find a route for 'GET: blog'.

Any idea why this is not working.

Website Traffic Drop After Migrating to Magento 2.4.7?

$
0
0
Hi everyone,

I recently upgraded my eCommerce website, PMKK Gems, from an older version of Magento to Magento 2.4.7. While the website is now running faster and smoother, I’ve noticed a big drop in organic traffic since the update.

We kept all the product data, design, and most of the URLs the same during the migration. Still, the drop in traffic is worrying. I think it might be due to some SEO settings, URL changes, redirects, or some missed configuration during the process.

Has anyone else faced the same issue after moving to Magento 2.4.7?
What are the most common SEO mistakes during a Magento migration that can cause traffic to drop?

I’d really appreciate any help or suggestions.
Thanks in advance!

Update from 4.6.0 to 4.6.1 failed

$
0
0
I got in trouble with latest update...it's my fault for sure but each update it's a pain.
I run composer update to update new files...then I downloaded the latest package and manually replaced the following files in the project space:
Code:
app/Config/Autoload.php

app/Config/Cache.php

app/Config/DocTypes.php

app/Config/Mimes.php

app/Config/Modules.php

app/Config/Optimize.php

app/Config/Paths.php

app/Views/errors/html/debug.css

preload.php

public/index.php

spark

Now, when I try to run spark serve file I got the follwoing error:
Code:
PHP Warning:  require(D:\_GAVS_nuovo_sito\project-root\app\Config/../../system/Boot.php): Failed to open stream: No such file or directory in D:\_GAVS_nuovo_sito\project-root\spark on line 85

Warning: require(D:\_GAVS_nuovo_sito\project-root\app\Config/../../system/Boot.php): Failed to open stream: No such file or directory in D:\_GAVS_nuovo_sito\project-root\spark on line 85
PHP Fatal error:  Uncaught Error: Failed opening required 'D:\_GAVS_nuovo_sito\project-root\app\Config/../../system/Boot.php' (include_path='.;C:\php\pear') in D:\_GAVS_nuovo_sito\project-root\spark:85
Stack trace:
#0 {main}
  thrown in D:\_GAVS_nuovo_sito\project-root\spark on line 85

Fatal error: Uncaught Error: Failed opening required 'D:\_GAVS_nuovo_sito\project-root\app\Config/../../system/Boot.php' (include_path='.;C:\php\pear') in D:\_GAVS_nuovo_sito\project-root\spark:85
Stack trace:
#0 {main}
  thrown in D:\_GAVS_nuovo_sito\project-root\spark on line 85

Honestly I have no idea what I did wrong...any hint or help? Thanks a lot

Sessions old files are deleted

$
0
0
Currently, within the Session library when using file - we see CI_Session_files_driver::read taking up to 120s to process 
Sessions old files are deleted but after some time I see still see these performance issues on requests tracked in NewRelic where it takes 100-120s

Setting baseURL in Registrar not working

$
0
0
Hey guys,
the registrar does not seem to work (at least for me). I followed th documentation and set it up like so:
-------------------
Code:
<?php

namespace Config;

class Registrar{

  public function __construct(){
    defined('LOCATION') || define('LOCATION', $_SERVER['CI_ENVIRONMENT']);
    }

  public static function App(): array{
     
    $conf = [];
    $conf['baseURL'] = 'http://192.168.0.1:81/'; 
    if(LOCATION == 'staging') $conf['baseURL'] = 'http://mydomain.com/';

    return $conf;

    }
  }
---------------------

I always get the error 
Fatal error: Uncaught CodeIgniter\Exceptions\ConfigException: Config\App::$baseURL "/" is not a valid URL. in ...\vendor\codeigniter4\framework\system\HTTP\SiteURI.php:201

Autodiscovery is set to true.
Its only workig if a manually set the baseURL in App.php but the URL should be set dynamically based on the environment. CI3 was way more comfortable and dynamic to set up.
Anybody knows the problem?

Thanks and kind regards,
Daniel

hot-reload side effects seem to be clobbering my app

$
0
0
Hi Team,
I am slowly losing the will ...
I think the debug toolbar and tracing is very helpful but at the moment my app is not behaving as expected ie serving a login view when someone logs out after redirect.
Looking at the FF java console I see messages like this:

The connection to https://localhost/__hot-reload was interrupted while the page was loading. login line 37 > injectedScript:702:29
EventSource failed:
error { target: EventSource, isTrusted: true, srcElement: EventSource, currentTarget: EventSource, eventPhase: 2, bubbles: false, cancelable: false, returnValue: true, defaultPrevented: false, composed: false, … }
login line 37 > injectedScript:710:21
    onerror https://localhost/login line 37 > injectedScript:710
    (Async: EventHandlerNonNull)
    hotReloadConnect https://localhost/login line 37 > injectedScript:709
    setHotReloadState https://localhost/login line 37 > injectedScript:697
    init https://localhost/login line 37 > injectedScript:27
    onreadystatechange https://localhost/?debugbar:49
    (Async: EventHandlerNonNull)
    loadDoc https://localhost/?debugbar:14
    (Async: EventListener.handleEvent)
    <anonymous> https://localhost/?debugbar:1
This page is in Quirks Mode. Page layout may be impacted. For Standards Mode use “<!DOCTYPE html>”. login
XHRGET
https://localhost/?debugbar_time=1747223756.436512
[HTTP/1.1 200 OK 78ms]

XHRGET
https://localhost/__hot-reload


At this moment I am trying to redirect to "https//localhost/login" which I have successfully proved works when I initially login, but once I logout and redirect back to the same place I never see the login screen again.
I am very frustrated and really cannot work out why.
Any help would be appreciated, Thx, Paul

Missing closing bracket when there is cached query & multiple nested bracket

$
0
0
There is an issue where 'closing bracket' does not appear when there is 'cached query' and 'multiple nested brackets'.

Here is the example code:
PHP Code:
// cached query
$this->db->start_cache();
$this->db->where("col_desc"'test_inside_bracket');
$this->db->stop_cache();

// add additional 'where' using bracket (used to implement 'keyset pagination')
$this->db->bracket();
    $this->db->bracket();
        $this->db->where("col_name > 'test_name'");
    $this->db->bracket_close();
    $this->db->or_bracket();
        $this->db->where("col_name = 'test_name'");
        $this->db->where("col_id < 12345");
    $this->db->bracket_close();
$this->db->bracket_close();
$this->db->order_by("col_name asc, col_id desc");

// check the query
$check_query $this->db->_get_select();
die(
$check_query); 

---
The result from code above is:
Code:
SELECT *
WHERE col_desc = 'test_inside_bracket'
AND  (
  (
col_name > 'test_name'
  )
OR    (
col_name = 'test_name'
AND col_id < 12345
)
ORDER BY col_name asc, col_id desc

The above result is missing 1 closing bracket.
The expected output should be like this:
Code:
SELECT *
WHERE col_desc = 'test_inside_bracket'
AND  (
  (
col_name > 'test_name'
  )
OR    (
col_name = 'test_name'
AND col_id < 12345
)
)
ORDER BY col_name asc, col_id desc

---
The issue above is gone when I remove the start_cache() and stop_cache() line (or one of those).
PHP Code:
// no cache, just plain where and some brackets
$this->db->where("col_desc"'test_inside_bracket');
$this->db->bracket();
    $this->db->bracket();
        $this->db->where("col_name > 'test_name'");
    $this->db->bracket_close();
    $this->db->or_bracket();
        $this->db->where("col_name = 'test_name'");
        $this->db->where("col_id < 12345");
    $this->db->bracket_close();
$this->db->bracket_close();
$this->db->order_by("col_name asc, col_id desc");

// check the query
$check_query $this->db->_get_select();
die(
$check_query); 

And the issue above is also gone when there is only one nested bracket:
PHP Code:
// cached query
$this->db->start_cache();
$this->db->where("col_desc"'test_inside_bracket');
$this->db->stop_cache();

// add additional 'where' using bracket (used to implement 'keyset pagination')
$this->db->bracket();
    $this->db->bracket();
        $this->db->where("col_name > 'test_name'");
    $this->db->bracket_close();
    // $this->db->or_bracket(); // if this bracket (and closing bracket) is uncommented, the closing bracket will be missing
    //    $this->db->where("col_name = 'test_name'");
    //    $this->db->where("col_id < 12345");
    // $this->db->bracket_close();
$this->db->bracket_close();
$this->db->order_by("col_name asc, col_id desc");

// check the query
$check_query $this->db->_get_select();
die(
$check_query); 

---
Please help with the issue above.
Any feedback / workaround would be greatly appreciated.
Thank you.

NB:
Temporary solusion for that issue is doing 'cache query' manually (put the query in function, then call that function to get the query. Not using start_cache()).
Viewing all 14343 articles
Browse latest View live


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