Codeigniter A PHP Error was encountered – Trying to access array offset on value of type null

A PHP Error was encountered
Severity: Notice

Message: Trying to access array offset on value of type null

Filename: helpers/common_helper.php

Line Number: 35

Backtrace:

File: F:xampphtdocssdpnew1applicationhelperscommon_helper.php
Line: 35
Function: _error_handler

File: F:xampphtdocssdpnew1applicationcontrollersadminUsers.php
Line: 36
Function: get_admin_name

File: F:xampphtdocssdpnew1index.php
Line: 315
Function: require_once

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
// -----------------------------------------------------------------------------
// Get Language by ID
function get_lang_name_by_id($id)
{
    $ci = & get_instance();
    $ci->db->where('id',$id);
    return $ci->db->get('ci_language')->row_array()['name'];
}

// -----------------------------------------------------------------------------
// Get Language Short Code
function get_lang_short_code($id)
{
    $ci = & get_instance();
    $ci->db->where('id',$id);
    return $ci->db->get('ci_language')->row_array()['short_name'];
}

// -----------------------------------------------------------------------------
// Get Language List
function get_language_list()
{
    $ci = & get_instance();
    $ci->db->where('status',1);
    return $ci->db->get('ci_language')->result_array();
}

// -----------------------------------------------------------------------------
// Get Admin name by ID
function get_admin_name($id)
{
    $ci = & get_instance();
    $ci->db->where('user_id',$id);
    $ret = $ci->db->get('ci_users')->row_array()['username']; // Problem area 
    if($ret === null || trim($ret) === '') //DH in case of the 'creator' has been deleted
        return 'Unknown';
    return $ret;
}

// -----------------------------------------------------------------------------
// Get country list
function get_country_list()
{
    $ci = & get_instance();
    return $ci->db->get('ci_countries')->result_array();
}

// -----------------------------------------------------------------------------
// Get country name by ID
function get_country_name($id)
{
    $ci = & get_instance();
    return $ci->db->get_where('ci_countries', array('id' => $id))->row_array()['name'];
}

// -----------------------------------------------------------------------------
// Get City ID by Name
function get_country_id($title)
{
    $ci = & get_instance();
    return $ci->db->get_where('ci_countries', array('slug' => $title))->row_array()['id'];
}

// -----------------------------------------------------------------------------
// Get country slug
function get_country_slug($id)
{
    $ci = & get_instance();
    return $ci->db->get_where('ci_countries', array('id' => $id))->row_array()['slug'];
}

// -----------------------------------------------------------------------------
// Get country's states
function get_country_states($country_id)
{
    $ci = & get_instance();
    return $ci->db->select('*')->where('country_id',$country_id)->get('ci_states')->result_array();
}

// -----------------------------------------------------------------------------
// Get state's cities
function get_state_cities($state_id)
{
    $ci = & get_instance();
    return $ci->db->select('*')->where('state_id',$state_id)->get('ci_cities')->result_array();
}

// Get state name by ID
function get_state_name($id)
{
    $ci = & get_instance();
    return $ci->db->get_where('ci_states', array('id' => $id))->row_array()['name'];
}

// -----------------------------------------------------------------------------
// Get city name by ID
function get_city_name($id)
{
    $ci = & get_instance();
    return $ci->db->get_where('ci_cities', array('id' => $id))->row_array()['name'];
}

// -----------------------------------------------------------------------------
// Get city ID by title
function get_city_slug($id)
{
    $ci = & get_instance();
    return $ci->db->get_where('ci_cities', array('id' => $id))->row_array()['slug'];
}

/**
 * Generic function which returns the translation of input label in currently loaded language of user
 * @param $string
 * @return mixed
 */
function trans($string) //DH modif
{
    $ci =& get_instance();
    // return $ci->lang->line($string); //DH : original line

    $tmp = $ci->lang->line($string);
    if( !empty($tmp) )
        return $tmp;
    return '!'. $string . '!';
}

My php mail does not show correct from and is showing html code

I have 2 problems. First when I get an email through my contact form the ‘from’ field is my e-mail and not client his email.
Second, my html code
is showing in the mail instead of making an enter.

<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

if(isset($_POST['submit'])){
    
    $name = stripcslashes($_POST['name']);   
    $phone = stripcslashes($_POST['phone']);
    $email = stripcslashes($_POST['email']);
    $message = stripcslashes($_POST['message']);
    
     $headers = 'From: [email protected]' . "rn" .
    'Reply-To: ' . $email . "rn" .
    'X-Mailer: PHP/' . phpversion();
    
    $subject = "Afspraak aanvraag van: " . $name;
    $message = "Naam: " . $name . "<br><br>E-mail: " . $email . "<br><br>Telefoon: " . $phone . "<br><br>Bericht: ". "Bericht: " . $message;
    mail('[email protected]',$subject,$message,$headers);
    
    
   if(mail($subject,$message,$headers)) {
        echo "<h3>Sorry, er ging iets mis.</h3>";
    } else {
        header('Location:https://tandartsenteam.be/bedankt');
    }
   }
?> 

Get database info in cart-detailed-product-line.tpl

I would need to get database info to be displayed in cart-detailed-product-line.tpl
I need to access the ps_cart table and display infos from a column I created in it. There already is a $cart variable available in this tpl file but it looks like it doesn’t get datas from ps_cart. I looked for the php file from where I could call those datas with SQL requests but I don’t get to find it…

How can I manage to do it ?

Create a tree view using php

I have this function that generates menu my problem is I have a specific design if there is a parent and when there is none.

Here is the sample array that I am generating:

{“ITEMS”:{“1”:{“MENU_ID”:”1″,”0″:”1″,”MENU”:”Settings”,”1″:”Settings”,”PARENT_MENU”:”0″,”2″:”0″,”IS_LINK”:0,”3″:0,”MENU_LINK”:null,”4″:null},”5″:{“MENU_ID”:”5″,”0″:”5″,”MENU”:”Views”,”1″:”Views”,”PARENT_MENU”:”0″,”2″:”0″,”IS_LINK”:1,”3″:1,”MENU_LINK”:”page.php?module=09&menu=0d”,”4″:”page.php?module=09&menu=0d”},”6″:{“MENU_ID”:”6″,”0″:”6″,”MENU”:”Plugins”,”1″:”Plugins”,”PARENT_MENU”:”0″,”2″:”0″,”IS_LINK”:1,”3″:1,”MENU_LINK”:”page.php?module=09&menu=0e”,”4″:”page.php?module=09&menu=0e”},”2″:{“MENU_ID”:”2″,”0″:”2″,”MENU”:”Modules”,”1″:”Modules”,”PARENT_MENU”:”1″,”2″:”1″,”IS_LINK”:1,”3″:1,”MENU_LINK”:”page.php?module=09&menu=0a”,”4″:”page.php?module=09&menu=0a”},”3″:{“MENU_ID”:”3″,”0″:”3″,”MENU”:”Models”,”1″:”Models”,”PARENT_MENU”:”1″,”2″:”1″,”IS_LINK”:1,”3″:1,”MENU_LINK”:”page.php?module=09&menu=0b”,”4″:”page.php?module=09&menu=0b”},”4″:{“MENU_ID”:”4″,”0″:”4″,”MENU”:”Menu Items”,”1″:”Menu Items”,”PARENT_MENU”:”3″,”2″:”3″,”IS_LINK”:1,”3″:1,”MENU_LINK”:”page.php?module=09&menu=0c”,”4″:”page.php?module=09&menu=0c”}},”PARENTS”:{“0”:[“1″,”5″,”6″],”1”:[“2″,”3″],”3”:[“4”]}}

The code below is my function that generates the html design of the menu.

I am having a hard time checking if the menu has a parent or not kindly see (if(in_array(, $menu[‘PARENTS’][0])){). What do I need to change in my code to che


public function generate_menu($parent, $menu){
        if ($this->databaseConnection()) {
            $menu_item = '';
            if (isset($menu['PARENTS'][$parent])) {
                foreach ($menu['PARENTS'][$parent] as $item_id) {
                    if (!isset($menu['PARENTS'][$item_id])) {
                       # if($menu['PARENTS'][0] != $menu['PARENTS'][$item_id]){
                        

                        // Here is my problem
                        if(in_array(, $menu['PARENTS'][0])){
                            //Without parent menu
                            $menu_item .= '<li class="nav-item dropdown"><a href="'. $menu['ITEMS'][$item_id]['MENU_LINK'] .'" class="nav-link">'. $menu['ITEMS'][$item_id]['MENU'] .'</a></li>';
                        }
                        else{
                            // With Parent menu
                            $menu_item .= '<a href="'. $menu['ITEMS'][$item_id]['MENU_LINK'] .'" class="dropdown-item"">'. $menu['ITEMS'][$item_id]['MENU'] .'</a>';
                        }


                    }
                    
                    if (isset($menu['PARENTS'][$item_id])) {
                        $menu_item .= '<li class="nav-item dropdown">
                                            <a class="nav-link dropdown-toggle arrow-none" href="javascript: void(0);" id="topnav-user-access" role="button">
                                                <span key="t-user-access">'. $menu['ITEMS'][$item_id]['MENU'] .'</span> <div class="arrow-down"></div>
                                            </a>';
                        $menu_item .= '<div class="dropdown-menu" aria-labelledby="topnav-user-access">';
                        $menu_item .= $this->generate_menu($item_id, $menu);
                        $menu_item .= '</div></li>';
                    }
                }
            }

            return $menu_item;
        }
    }

In which db table wpuf form saved?

I purchased the wpuf plugin, And created a form with multiple of check boxes for each section. Now already created the multiple check boxes section so, I wanted to display those check boxes in some other location using templates. How do find and fetch wpuf form fields from db?

I am trying to fetch it from db, Unable to find it

checkbox list is not opening

So i have a laravel website where i need to filter ‘file’s

the filter is for the ‘tags’ which are given to the file thru a pivot table

i have this piece of code for a dropdown with checkboxes as items.

all the code is placed in the same .php file

   <div wire:model="tag_id" wire:change="filter" id="list1" class="dropdown-check-list" tabindex="100">
            <span class="anchor">select tag </span>
            <ul class="items">
            @foreach ($categories as $category)
            <li> <input wire:model="tag_id" wire:change="filter" type="checkbox" value="{{$category->id}}"/>{{ $category->name}}</li>
            @endforeach
            <ul>
        </div>

css:

   <style>
        .dropdown-check-list {
  display: inline-block;
}

.dropdown-check-list .anchor {
  position: relative;
  cursor: pointer;
  display: inline-block;
  padding: 5px 50px 5px 10px;
  border: 1px solid #ccc;
}

.dropdown-check-list .anchor:after {
  position: absolute;
  content: "";
  border-left: 2px solid black;
  border-top: 2px solid black;
  padding: 5px;
  right: 10px;
  top: 20%;
  -moz-transform: rotate(-135deg);
  -ms-transform: rotate(-135deg);
  -o-transform: rotate(-135deg);
  -webkit-transform: rotate(-135deg);
  transform: rotate(-135deg);
}

.dropdown-check-list .anchor:active:after {
  right: 8px;
  top: 21%;
}

.dropdown-check-list ul.items {
  padding: 2px;
  display: none;
  margin: 0;
  border: 1px solid #ccc;
  border-top: none;
}

.dropdown-check-list ul.items li {
  list-style: none;
}

.dropdown-check-list.visible .anchor {
  color: #0094ff;
}

.dropdown-check-list.visible .items {
  display: block;
}
    </style>

script

   <script>
        var checkList = document.getElementById('list1');
checkList.getElementsByClassName('anchor')[0].onclick = function(evt) {
  if (checkList.classList.contains('visible'))
    checkList.classList.remove('visible');
  else
    checkList.classList.add('visible');
}
    </script>

enter image description here
as you can see there is a dropdown, but it is not clickable. whenever i inspect it i can see the UL items. i followed the code found here: How to create checkbox inside dropdown?

Aws Cognito PHP SDK not returning custom attributes for SAML with Microsoft Active Directory

We are using the AWS Cognito PHP SDK, last version ( https://github.com/aws/aws-sdk-php ).

We have configured the Microsoft ACtive Directory and AWS Cognito link, by creating an attribute in AD and later by creating a Custom Attribute in Cognito, to map to the AD’s attribute schema, such as:

enter image description here

For custom:UsersRole attribute, we also tried with the full schema path: http://schemas.xmlsoap.org/ws/…/userextendedattribute2 but it’s still now working.

We have followed the documentation from: https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pools-specifying-attribute-mapping.html and https://medium.com/@zippicoder/setup-aws-cognito-user-pool-with-an-azure-ad-identity-provider-to-perform-single-sign-on-sso-7ff5aa36fc2a

The link between AD and Cognito is well configured, the custom attributes were given read/write permissions and the “profile” permissions are also enabled in Cognito.

We have tried to use the getUser and listUsers ( https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-cognito-idp-2016-04-18.html#getuser and https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-cognito-idp-2016-04-18.html#listusers ) methods, to read the attributes, but both of them return the following data:

"Attributes"
        =>array(2){
          [
            0
          ]=>array(2){
            [
              "Name"
            ]=>string(3)"sub"[
              "Value"
            ]=>string(36)"6asdsadasd-dsadasd-asdasd"
          }[
            1
          ]=>array(2){
            [
              "Name"
            ]=>string(10)"identities"[
              "Value"
            ]=>string(201)"[{"userId":"[email protected]","providerName":"ourprovidername","providerType":"SAML","issuer":"https: //sts.windows.net/123213213-123123cx3123-12321321/","primary":true,"dateCreated":1664952636840}]"
          }
        }

We have two attributes that are not being returned: Email and custom:UsersRole. We are receiving the email under the userId attribute name, under the identities attribute, but how can we ask for and receive the custom attribute custom:UsersRole?

Any help will be great, thank you.

Laravel: Convert an upload action into a array with foreach

I have a dynamic action class that is reusable through the entire app UploadImageAction

It handles single image upload per request:

class UploadImageAction implements UploadImageContract
{
    public function handle(Request $request, $imageProperty, $image, $imageDir)
    {
        if ($request->hasFile($imageProperty)) {
            // Handle uploading lf_image
            if (!is_null($image) && Storage::exists($image)) {
                // Throw exceptions here
                Storage::delete($image);
            }
            // Throw exceptions here
            return $request->file($imageProperty)->store($imageDir);
        }
    }
}

The way I handle the action is by creating a method in service class:

protected function handleAttachments($request, $report)
    {
        // Handle Attachments
        $uploadImageAction = resolve(UploadImageAction::class);

        // Handle lf_image action
        if($request->hasFile('attachments')) {
            $report->attachments = $uploadImageAction->handle($request, 'attachments', $report->attachments, 'incidents');
        }

        return $report;
    }

Then call in within the storeReport():

$report = Report::create($request->validated());
$report = $this->handleAttachments($request, $report); // Called here

What I’m trying to do is make it possible to upload multiple images, I wrote the below code block in the storeReport method in Service class just to test (commented out the handleAttachments()):

$ir_counter = $report->ir_number->prefix ?? 'IR#' . str_pad($report->ir_number, 4, '0', STR_PAD_LEFT);
        $attachments = [];

        if($request->hasfile('attachments'))
        {
            foreach($request->file('attachments') as $attachment)
            {
                $name = time().rand(100, 1000) . '.' . $attachment->extension();
                $attachment->move(public_path('app/incident/' . $ir_counter . '/'), $name);
                $attachments[] = $name;
            }
        }

        $report->attachments = implode('|', $attachments);

It’s working as expected. But how can I reflect the array/loop in the UploadImageAction code? When I try to do so, the DB column of attachments shows: [{}].

PHP + ReactDom.render() not loading component contents

I’m trying to load a react component to my PHP file (.pthml).

It add the component tag but the component contents are not rendered.

ReactDom.render(
    React.createElement('ProductFiltersComponent', {}),
    document.getElementById('sub-header')
);

This is how it’s added to the php file.

enter image description here

This is the component’s contents,

enter image description here

How should the react component be loaded?

How to return Model Method as Response in api

I have a method called show at the Product Model which returns a resource for api results:

public function show(Product $product): ProductResource
    {
        return (new ProductResource($product))->additional([
            'gallery' => $product->photos->pluck('image')
                ->transform(fn ($v) => Storage::disk('public')->url($v))
        ]);
    }

Now I have defined a method called similarProductsBasedOnBrand at the Product Model which goes like this:

public function similarProductsBasedOnBrand($brand_id)
    {
        return Category::find($brand_id)->products()->get();
    }

But don’t know how to get results from this method in api result of show()!

So if you know how to return the results of similarProductsBasedOnBrand in the response of show method, please let me know… I really need this.

Thanks

Laravel/PHP flatten multidimensional array

I’m wondering if someone can help with the following please? Currently I have this array:

    array:1 [
      "blocks" => array:3 [
        0 => array:1 [
          "component" => "TextColumns"
        ]
        1 => array:2 [
          0 => array:1 [
            "component" => "TextColumns"
          ]
          1 => array:1 [
            "component" => "TextColumns"
          ]
        ]
        2 => array:1 [
          "component" => "TextColumns"
        ]
      ]
    ]

What I want to achieve is a final array of the below:

    array:1 [
      "blocks" => array:3 [
        0 => array:1 [
          "component" => "TextColumns"
        ]
        1 => array:1 [
          "component" => "TextColumns"
        ]
        2 => array:1 [
          "component" => "TextColumns"
        ]
        3 => array:1 [
          "component" => "TextColumns"
        ]
      ]
    ]

If I use array_flatten or laravels ->flatten() I do not get the desired results as it flattens it too much:

    array:1 [
      "blocks" => array:3 [
        0 => array:1 [
          "component" => "TextColumns"
        ]
        1 => array:2 [
          0 => "TextColumns"
          1 => "TextColumns"
        ]
        2 => array:1 [
          "component" => "TextColumns"
        ]
      ]
    ]

Any help would be appreciated!

Thanks

Update items within php objects [duplicate]

I want to update the Content string within the object. With the first foreach I get this:

object(Page)#1716 (20) {
        ["_cache_statusFlags":protected]=> NULL
        ["creatableChildrenCache":protected]=> NULL
        ["destroyed"]=> bool(false)
        ["record":protected]=> array(22) {
          ["ClassName"]=> string(4) "Page"
          ["ID"]=> int(1)
          ["ParentID"]=> int(0)
          ["Title"]=> string(5) "Home"
          ["MenuTitle"]=> NULL
          ["URLSegment"]=> string(4) "home"
          ["Content"]=> string(2210) "
My content that needs to be updated
"...

I tried with json_decode, (array) but I either get “Uncaught Error: Cannot use object of type Page as array” or no error and no update.

// json_decode($results,true);
foreach ($results as $result) {
   json_decode($result,true); // seem like it does nothing
   // tried (array)$result['record']['Content'], (array)$result['Content'],...
   // $result['Content'] = str_replace($keywords,'<span class="highlight-search">' .$keywords . '</span>',$result->Content);
   $result['record']['Content'] = str_replace($keywords,'<span class="highlight-search">' .$keywords . '</span>',$result->Content);
}

I also tried with foreach($result as $key => $field)…

At this point I’m just guessing. What is the proper procedure?

Upgrading to PHP8 In XAMPP Goes Wrong

I’m using XAMPP v3.2.4 and the PHP version was 7.4, so I downloaded the latest version of XAMPP and copied the php folder to my xampp directory and renamed the old version of php to php7.4.

Then I followed these steps to complete the upgrading:

httpd-xampp.conf:

Replaced php7 to php8

Replaced php7_module to php_module

Then inside php.ini, set the absolute paths like xamppphp to C:xamppphp

But now when I restart the XAMPP, I cannot run Apache and get this error:

01:28:11   [Apache]     Error: Apache shutdown unexpectedly.
01:28:11   [Apache]     This may be due to a blocked port, missing dependencies, 
01:28:11   [Apache]     improper privileges, a crash, or a shutdown by another method.
01:28:11  [Apache]  Press the Logs button to view error logs and check
01:28:11  [Apache]  the Windows Event Viewer for more clues
01:28:11  [Apache]  If you need more help, copy and post this
01:28:11  [Apache]  entire log window on the forums

So it says can not start Apache due to a blocked port but it used to be run properly with the older version!

So what’s going wrong here? How can I solve this issue?

How to convert PHP date to Excel in prefer format?

Can anyone help me in converting the below date format in PHP into the preferred format?

if I export to excel format (.XLSX) it turned like 01-01-2022. however, I prefer to be formatted like this 01/01/2022.

but If I export it as CSV file, there is no problem

enter image description here

Como enviar datos de un console.log de javascript a la base de datos [closed]

soy novato, quiero enviar los datos capturados en un console.log de JavaScript a una base de datos MySql.

Tengo un console.log que me muestra en consola la altitud y longitud de una localizacion. Me gastaría capturar esos datos y enviarlos a una base de datos.

Este es el código que llevo por el momento y no se como hacer el siguiente paso.

    enableHighAccuracy: true,
    timeout: 6000,
    maximumAge: 0
  };
  
  navigator.geolocation.getCurrentPosition( success, error, options );
  
  function success(position) {
    var coordenadas = position.coords;
  
    console.log('Tu posición actual es:');
    console.log('Latitud : ' + coordenadas.latitude);
    console.log('Longitud: ' + coordenadas.longitude);
    console.log('Más o menos ' + coordenadas.accuracy + ' metros.');
  };
  
  function error(error) {
    console.warn('ERROR(' + error.code + '): ' + error.message);
  };```


(Tambien tengo la conexión a la base de datos).