Symfony – Sending Failed Messages on purpose

I’m currently using Messenger to send mails with Mailer through my MessageHandler.

Here’s my messenger.yaml config file.

# config/packages/messenger.yaml
framework:
    messenger:
        transports:
            async: 
                dsn: '%env(MESSENGER_TRANSPORT_DSN)%'
                options:
                      table_name: messenger_message

            failed:
                dsn: '%env(MESSENGER_TRANSPORT_DSN)%'
                options:
                    queue_name: failed
                    table_name: messenger_message_failed

        routing:
            AppMessageSendEmailMessage: async

How can I send failed messages on purpose to see if my messenger_message_failed receives the data ?

I am new to creating websites and need help in coding a website that will store user logins in a database when they sign up [closed]

I am new and don’t have idea how it will be done.

hello greetings,
I am trying to create a website that will allow visitors sign up and login later using their username/email and password will create a user and store in an sql table called users.so when they later choose to sign in, it will connect to a database and match the details and if matching a stored login will connect to their profile. more like how websites like sites like Facebook works ( when you login it goes to your page and not someone). I am completely new but bellow is my sign up page.

how do i connect the a database and allow them login next time. Thank you everyone.

I am completely new and learning

<!-- language: lang-html -->

    <!DOCTYPE html>
       <html lang="en">
       <head>
          <meta charset="UTF-8">
          <meta name="viewport" content="width=device-width, initial-scale=1.0">

          <!--=============== REMIXICONS ===============-->
          <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/remixicon/3.5.0/remixicon.css" crossorigin="">

          <!--=============== CSS ===============-->
          <link rel="stylesheet" href="assets/css/styles.css">

          <title>Learn Login an Sign up</title>
       </head>
       <body>
          <div class="login">
             <img src="assets/img/login-bg.png" alt="image" class="login__bg">

             <form action="" class="login__form">
                <h1 class="login__title">Register</h1>

                <div class="login__inputs">
                   <div class="login__box">
                      <input type="email" placeholder="Username" required class="login__input">
                      <i class="ri-mail-fill"></i>
                   </div>

                <div class="login__inputs">
                   <div class="login__box">
                      <input type="email" placeholder="Full Name" required class="login__input">
                      <i class="ri-mail-fill"></i>
                   </div>
                    
                <div class="login__inputs">
                   <div class="login__box">
                      <input type="email" placeholder="Email ID" required class="login__input">
                      <i class="ri-mail-fill"></i>
                   </div>
                   <div class="login__box">
                      <input type="password" placeholder="Password" required class="login__input">
                      <i class="ri-lock-2-fill"></i>
                   </div>
                    <div class="login__box">
                      <input type="password" placeholder="Confirm Password" required class="login__input">
                      <i class="ri-lock-2-fill"></i>
                   </div>
                </div>

                

                <button type="submit" class="login__button">Register</button>

                <div class="login__register">
                   Already have an account?  <a href="index.html">Login</a>
                </div>
             </form>
          </div>
       </body>
    </html>

<!-- end snippet -->

I am unable to create a database and connected to which will create a new user table for new registration and store details

Find consecutive occurrences in multidimensional array php

Array
(
    [0] => Array
        (
            [0] => OLAO01
            [1] => OLAO01
            [2] => BARR04
            [3] => OLAO01
            [4] => MADD03
        )

    [1] => Array
        (
            [0] => BARR04
            [1] => POWE03
        )

    [2] => Array
        (
            [0] => BARR04
            [1] => COLL09
        )

    [3] => Array
        (
            [0] => BARR04
            [1] => SARC01
            [2] => OLAO01
        )

    [4] => Array
        (
            [0] => BARR04
            [1] => HORS02
        )

    [5] => Array
        (
            [0] => BARR04
        )

    [6] => Array
        (
            [0] => OLAO01
        )

    [7] => Array
        (
            [0] => RYDE02
        )

    [9] => Array
        (
            [0] => CAMP02
        )

    [10] => Array
        (
            [0] => WRIG05
            [1] => CAMP02
            [2] => LEMO01
        )

    [11] => Array
        (
            [0] => OLAO01
        )

    [12] => Array
        (
            [0] => HIPP01
            [1] => LEMO01
        )
)

I have array like this I needs to find if how many time one value repeating consecutive BARR04

Repeated 6 times. But if one array not that value then for that counter it will set to 1 again

$result = array_intersect($newary[$i], $newary[$i+1]);  

I tried with this but not working properly

Symfony/composer showing Deprecated errors with php8.2

I am trying to get the latest version of mPDF for my recently upgraded (centos) dev php environment (now on php 8.2.10) but I am getting the following Symfony error:

$ composer require mpdf/mpdf

Deprecated: Return type of SymfonyComponentConsoleHelperHelperSet::getIterator() should either be compatible with IteratorAggregate::getIterator(): Traversable, or the #[ReturnTypeWillChange] attribute should be used to temporarily suppress the notice in /usr/share/php/Symfony3/Component/Console/Helper/HelperSet.php on line 104
Deprecation Notice: strlen(): Passing null to parameter #1 ($string) of type string is deprecated in /usr/share/php/JsonSchema5/Constraints/Constraint.php:48
Deprecation Notice: Return type of SymfonyComponentProcessProcess::getIterator($flags = 0) should either be compatible with IteratorAggregate::getIterator(): Traversable, or the #[ReturnTypeWillChange] attribute should be used to temporarily suppress the notice in /usr/share/php/Symfony3/Component/Process/Process.php:567
Deprecation Notice: Return type of ComposerRepositoryArrayRepository::count() should either be compatible with Countable::count(): int, or the #[ReturnTypeWillChange] attribute should be used to temporarily suppress the notice in /usr/share/php/Composer/Repository/ArrayRepository.php:286
Deprecation Notice: Return type of ComposerRepositoryArrayRepository::count() should either be compatible with Countable::count(): int, or the #[ReturnTypeWillChange] attribute should be used to temporarily suppress the notice in /usr/share/php/Composer/Repository/ArrayRepository.php:286
Deprecation Notice: Return type of ComposerRepositoryArrayRepository::count() should either be compatible with Countable::count(): int, or the #[ReturnTypeWillChange] attribute should be used to temporarily suppress the notice in /usr/share/php/Composer/Repository/ArrayRepository.php:286
Deprecation Notice: Using ${var} in strings is deprecated, use {$var} instead in /usr/share/php/Composer/Autoload/AutoloadGenerator.php:799
Deprecation Notice: Using ${var} in strings is deprecated, use {$var} instead in /usr/share/php/Composer/Autoload/AutoloadGenerator.php:804
Do not run Composer as root/super user! See https://getcomposer.org/root for details

Where do I go with this?

(PS. I’m no sysadmin expert here…I dev well but I don’t admin well. Any assistance would be grateful)

Edit #1 – added version information:

$ composer --version

Deprecated: Return type of SymfonyComponentConsoleHelperHelperSet::getIterator() should either be compatible with IteratorAggregate::getIterator(): Traversable, or the #[ReturnTypeWillChange] attribute should be used to temporarily suppress the notice in /usr/share/php/Symfony3/Component/Console/Helper/HelperSet.php on line 104
Deprecation Notice: strlen(): Passing null to parameter #1 ($string) of type string is deprecated in /usr/share/php/JsonSchema5/Constraints/Constraint.php:48
Deprecation Notice: Return type of SymfonyComponentProcessProcess::getIterator($flags = 0) should either be compatible with IteratorAggregate::getIterator(): Traversable, or the #[ReturnTypeWillChange] attribute should be used to temporarily suppress the notice in /usr/share/php/Symfony3/Component/Process/Process.php:567
Deprecation Notice: Return type of ComposerRepositoryArrayRepository::count() should either be compatible with Countable::count(): int, or the #[ReturnTypeWillChange] attribute should be used to temporarily suppress the notice in /usr/share/php/Composer/Repository/ArrayRepository.php:286
Deprecation Notice: Return type of ComposerRepositoryArrayRepository::count() should either be compatible with Countable::count(): int, or the #[ReturnTypeWillChange] attribute should be used to temporarily suppress the notice in /usr/share/php/Composer/Repository/ArrayRepository.php:286
Deprecation Notice: Return type of ComposerRepositoryArrayRepository::count() should either be compatible with Countable::count(): int, or the #[ReturnTypeWillChange] attribute should be used to temporarily suppress the notice in /usr/share/php/Composer/Repository/ArrayRepository.php:286
Deprecation Notice: Using ${var} in strings is deprecated, use {$var} instead in /usr/share/php/Composer/Autoload/AutoloadGenerator.php:799
Deprecation Notice: Using ${var} in strings is deprecated, use {$var} instead in /usr/share/php/Composer/Autoload/AutoloadGenerator.php:804
Do not run Composer as root/super user! See https://getcomposer.org/root for details
Continue as root/super user [yes]?
Composer 2.1.3 2021-06-09 16:31:20

PHP JS No ‘Access-Control-Allow-Origin’

I try to do a XMLHttpRequest from Javascript to a PHP script. Both are on the same server, but get the Error message:

myDomain.de/:1 Access to XMLHttpRequest at 'https://www.myDomain.de/test/lastId.php' from
origin 'https://myDomain.de' has been blocked by CORS policy: Response to preflight 
request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is 
present on the requested resource.

What’s the problem?
I tried Chrome and Edge as browser.

Thanks,
Stephan

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

header('Access-Control-Allow-Origin: https://www.myDomain.de');
header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
header("Access-Control-Allow-Headers: *");

return "helloFromServer";
?>
function easy() {
  const xhr = new XMLHttpRequest();
  const url = "https://www.myDomain.de/test/lastId.php"  
  xhr.onreadystatechange = function () {
    if (this.readyState == 4 && this.status == 200) {
      console.log("succeed");
    } else {
      console.log("failure");
    }
  };
  xhr.open("GET", url);
  xhr.setRequestHeader("Access-Control-Allow-Origin", "https://www.myDomain.de");
  xhr.setRequestHeader("Access-Control-Allow-Methods", "*");
  xhr.setRequestHeader("Access-Control-Allow-Headers", "*");
  xhr.send();
}

Javascript keeps running when the target element is removed/replaced

I am developing an auction site on wordpress with woocommerce that requires countdown timer to show when the auction for a specific product is ending.
Following is the coundowntimer JS:

        const dollersign = elem => document.querySelector(elem);
        const countdown = function(_config) {
          const tarDate = dollersign(_config.target).getAttribute('data-date').split('-');
          const day = parseInt(tarDate[2]);
          const month = parseInt(tarDate[1]);
          const year = parseInt(tarDate[0]);
          let tarTime = dollersign(_config.target).getAttribute('data-time');
          let tarhour, tarmin;
          if (tarTime != null) {
            tarTime = tarTime.split(':');
            tarhour = parseInt(tarTime[0]);
            tarmin = parseInt(tarTime[1]);
          }
          let months = [31, new Date().getFullYear() % 4 == 0 ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
          let dateNow = new Date();
          let dayNow = dateNow.getDate();
          let monthNow = dateNow.getMonth() + 1;
          let yearNow = dateNow.getFullYear();
          let hourNow = dateNow.getHours();
          let minNow = dateNow.getMinutes();
          let count_day = 0, count_hour = 0, count_min = 0;
          let count_day_isSet = false;
          let isOver = false;
          // Set the date we're counting down to
          const countDownDate = new Date(year, month-1, day, tarhour, tarmin, 0, 0).getTime();
          //$(_config.target+'  .day .word').innerHTML  = _config.dayWord;
          //$(_config.target+'  .hour .word').innerHTML = _config.hourWord;
          //$(_config.target+'  .min .word').innerHTML  = _config.minWord;
          //$(_config.target+'  .sec .word').innerHTML  = _config.secWord; 
          const updateTime = () => {
            // Get todays date and time
            const now = new Date().getTime();
            // Find the distance between now an the count down date
            const distance = countDownDate - now;
            // Time calculations for days, hours, minutes and seconds
            const days    = Math.floor(distance / (1000 * 60 * 60 * 24));
            const hours   = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
            const minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
            const seconds = Math.floor((distance % (1000 * 60)) / 1000);
            // If the count down is over, write some text
            if (distance <= 0) {
                dollersign(_config.target).innerHTML = "EXPIRED";
            } else {
                requestAnimationFrame(updateTime);
                if(days!=0){
                    dollersign(_config.target+' .day  .num').innerHTML = addZero(days);
                }
                if(_config.target != null){
                    dollersign(_config.target+' .hour .num').innerHTML = addZero(hours);
                    dollersign(_config.target+' .min  .num').innerHTML = addZero(minutes);
                    dollersign(_config.target+' .sec  .num').innerHTML = addZero(seconds);
                }  
            }
          }
          updateTime();
        }
        const addZero = (x) => (x < 10 && x >= 0) ? "0"+x : x;

This is how you can use it in an HTML block:

            <div class="countdown countdown-main" data-date="2023-09-25" data-time="18:00">
                <h4>
                    <span class="day"><span class="num"></span><span class="word"></span></span> 
                    <span class="hour"><span class="num"></span></span>:
                    <span class="min"><span class="num"></span></span>:
                    <span class="sec"><span class="num"></span></span>
                </h4>
            </div>
            <script>
            jQuery(document).ready(function() {
                setTimeout(function(){
                const myCountdown = new countdown({
                      target:  ".countdown",
                      dayWord: " zile",
                      hourWord:" ore",
                      minWord: " minute",
                      secWord: " secunde"
                });
                }, 1000);  
            });
            </script>

It works like a charm. But the problem is when you have to do query with ajax asin without loading the page. The script looks for the element that is removed, and throws long list of js error in the inspect element:
Uncaught TypeError: dollersign(…) is null
countdown.js?ver=1.0.0:49

I know you can use GET method and reload the page but is there any way to resolve this?

Thanks,

Bypass PECL ssl connection in Docker

I need to mantain a legacy sowftware, developing with docker with Jessie php:7.0.17-fpm.

I need to install a software from PECL but I get:

#0 2.359 WARNING: channel "pecl.php.net" has updated its protocols, use "pecl channel-update pecl.php.net" to update
#0 2.596 Could not download from "https://pecl.php.net/get/oci8-2.1.3.tgz", cannot download "pecl/oci8" (Connection to `ssl://pecl.php.net:443' failed: )
#0 2.596 Error: cannot download "pecl/oci8"
#0 2.597 Download failed
#0 2.597 install failed

And this is the relevant section of Docker:

# Install Oracle extensions
RUN pecl channel-update pecl.php.net pecl update-channels; rm -rf /tmp/pear ~/.pearrc
RUN echo 'instantclient,/opt/oracle/instantclient_12_1/' | pecl install oci8-2.1.3  
      && docker-php-ext-enable 
               oci8  
       && docker-php-ext-configure pdo_oci --with-pdo-oci=instantclient,/opt/oracle/instantclient_12_1,12.1 
       && docker-php-ext-install 
               pdo_oci

I’m lookig for a mode to skip the SSL check. It is an internal image.

I added as requested from PECL RUN pecl channel-update pecl.php.net pecl update-channels; rm -rf /tmp/pear ~/.pearrc but I cannot solve.

Thank you

Deploy issues with Symfony Project – JWT

I am trying to put my symfony project online by deploying it. Everytime I try to deploy it i got this messages.

Your lock file does not contain a compatible set of packages. Please run composer update. Problem 1 - lcobucci/jwt is locked to version 5.0.0 and an update of this package was not requested. - lcobucci/jwt 5.0.0 requires ext-sodium * -> it is missing from your system. Install or enable PHP's sodium extension. Problem 2 - lcobucci/jwt 5.0.0 requires ext-sodium * -> it is missing from your system. Install or enable PHP's sodium extension. - lexik/jwt-authentication-bundle v2.19.1 requires lcobucci/jwt ^3.4|^4.1|^5.0 -> satisfiable by lcobucci/jwt[5.0.0]. - lexik/jwt-authentication-bundle is locked to version v2.19.1 and an update of this package was not requested. To enable extensions, verify that they are enabled in your .ini files: - /app/vendor/php/etc/php.ini - /app/vendor/php/etc/conf.d/apcu.ini - /app/vendor/php/etc/conf.d/mongodb.ini - /app/vendor/php/etc/conf.d/opcache.ini - /app/vendor/php/etc/conf.d/redis.ini You can also run php –iniin a terminal to see which files are used by PHP in CLI mode. Alternatively, you can run Composer with–ignore-platform-req=ext-sodium` to temporarily ignore these required extensions.
! An error occurred during buildpack compilation
! Error deploying the application
! → Invalid return code from buildpack

Which is weird because sodium is activate, I made composer update and all other things written here

By using Filamentphp, why does my TextInput won’t automatically load any data from database?

So I am working on a project using laravel and filamentphp 3.x.
I experienced problems when I wanted to change the order record where the price should appear automatically.
I had the Orders table and Products table, and the price value is stored in Products table.

products table:

public function up(): void
    {
        Schema::create('orders', function (Blueprint $table) {
            $table->id();
            $table->foreignIdFor(User::class);
            $table->foreignIdFor(Products::class);
            $table->string('order_code')->unique();
            $table->unsignedInteger('quantity');
            // $table->decimal('unit_price', '10', 2);
            $table->string('status')->default('pending');
            $table->timestamps();
        });
    }

orders table:

public function up(): void
    {
        Schema::create('products', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('slug')->unique();
            $table->text('description')->nullable();
            $table->string('features');
            $table->unsignedBigInteger('price');
            $table->dateTime('start_at')->nullable();
            $table->boolean('is_visible')->default(true);
            $table->boolean('is_featured')->default(false);
            $table->longText('image')->nullable();
            $table->timestamps();
        });
    }

Order models:

public function products()
    {
        return $this->belongsTo(Products::class);
    }

OrderResource.php:

Group::make()->schema([
    Section::make()->schema([
        Select::make('products_id')
            ->label('Product')
            ->options(Products::query()->pluck('name', 'id'))
            ->native(false)
            ->reactive()
            ->afterStateUpdated(fn ($state, Set $set) =>
            $set('price', Products::find($state)?->price ?? 0)),
        TextInput::make('quantity')
            ->numeric()
            ->default(1)
            ->required()
            ->live()
            ->dehydrated(),
        TextInput::make('price')
            ->label('Price')
            ->prefix('IDR')
            ->disabled()
            ->dehydrated()
            ->numeric()
            ->required(),
        Placeholder::make('gross_amount')
            ->label('Total Price')
            ->content(function ($get) {
                return $get('quantity') * $get('price');
            }),
    ])
])

I tried to make some change to TextInput::make(‘price’) to this:

TextInput::make('price')
    ->label('Price')
    ->prefix('IDR')
    ->disabled()
    ->dehydrated()
    ->numeric()
    ->required()
    ->default(function ($record) {
        return $record->product ? $record->product->price : 0;
    }),

but it still not return any price value.

and then I tried to add a price column to the order table but why do I have to add a price column if I already have price in the product table?

PHP mysqli fetches rows that do not match the query

I am trying to fetch some rows with php mysqli based on what the type column is, however the results do not match the query.

My current code is this:

$stmt = $conn->prepare("SELECT * FROM additional_info WHERE type = ?");
$stmt->bind_param("i", $order["type"]);
$stmt->execute();
$result = $stmt->get_result();
$additional_info = $result->fetch_all(MYSQLI_ASSOC);

If I try to fetch with a type that is not in the rows, instead of returning an empty array or null it is returning all the rows. Am I missing something?

Pivote table (assosiative array) data in php

I have data in the following format returned from my database:

user_id | video_id | liked
0         341       1
1         765       1
0         534       1
3         981       1

I need to pivot this table into the following form:

user_id | 341 | 765 | 534 | 981
0         1     0     1     0
1         0     1     0     0
3         0     0     0     1

What I’m doing is making a single row per user id and a single column per video id, 0 should be the default value unless the video is liked.

For my initial testing and experimentation I was using python’s pandas library like so:

df = pd.read_csv('data.csv')
pivoted_df = df.pivot_table(
    index='user_id',
    columns='video_id',
    values='liked',
    fill_value=0,
)
pivoted_df.to_csv('pivoted_data.csv')

This is easy and works perfectly, but now I need to do the same in php and I couldn’t find any pandas alternatives. The other solutions I’ve seen use key names for columns that don’t work here since the columns can be any number.

To be clear about the actual data structure in php, the fetched data from the database looks as follows:

Array
(
    [0] => Array
        (
            [user_id] => 0
            [video_id] => 341
            [liked] => 1
        )

    [1] => Array
        (
            [user_id] => 1
            [video_id] => 765
            [liked] => 1
        )

    [2] => Array
        (
            [user_id] => 0
            [video_id] => 534
            [liked] => 1
        )

    [3] => Array
        (
            [user_id] => 3
            [video_id] => 981
            [liked] => 1
        )
)

And it needs to look like this:

Array
(
    [0] => Array
        (
            [user_id] => 0
            [341] => 1
            [765] => 0
            [534] => 1
            [981] => 0
        )

    [1] => Array
        (
            [user_id] => 1
            [341] => 0
            [765] => 1
            [534] => 0
            [981] => 0
        )

    [2] => Array
        (
            [user_id] => 3
            [341] => 0
            [765] => 0
            [534] => 0
            [981] => 1
        )
)

Warning Undefined array key “HTTP_STRIPE_SIGNATURE”

I’m getting:

warning Undefined array key “HTTP_STRIPE_SIGNATURE”

When I visit https:/example.com/webhook.php. That is the page where I have this code:

<?php

require "..../stripe-php-11.0.0/init.php";

// Your Stripe webhook endpoint secret
$webhook_secret = "whsec_...";

// Initialize Stripe with your secret API key
StripeStripe::setApiKey("sk_test_....");

// Get the raw request body and Stripe signature header
$payload = file_get_contents("php://input");
$sig_header = $_SERVER["HTTP_STRIPE_SIGNATURE"];

try {
    // Verify the signature
    $event = StripeWebhook::constructEvent(
        $payload,
        $sig_header,
        $webhook_secret,
    );
} catch (Exception $e) {
    // Invalid signature or other error
    http_response_code(400);
    exit();
}

// Handle the event
switch ($event->type) {
    case "checkout.session.completed":
        $session = $event->data->object;

        // Process the 'checkout.session.completed' event here
        // You can retrieve information about the completed session in $session

        // Example: Send a confirmation email to the customer
        // mail($session->customer_email, 'Order Confirmation', 'Thank you for your purchase!');
        $sessionId = $session->id;

        // Implement your logic to initiate the file download here
        http_response_code(200); // Acknowledge receipt of the event
        break;

    // Add more cases to handle other types of events as needed
    // case 'invoice.paid':
    //     // Handle invoice paid event
    //     break;

    default:
        // Unknown event type
        http_response_code(200);
        break;
}

I have already configured the webhook to point to the webhook URL and I checked and a successful stripe-signature was there after a successful checkout event. It’s just not verifying it when I go to the site manually. I’ve already had events sent there I can see it on the dashboard. I obviously replaced all the '...' in my code with the correct stuff. How do I fix this?

Laravel Missing required parameter

Missing required parameter for [Route: admin.ads.update] [URI: admin/ads/{ad}] [Missing parameter: ad].

i can’t retrieve data by id parameter {{route(‘admin.ads.update’, $adslist->id)}}
i don’t know what i miss please help me am just junior.

Laravel 10 respond

my code will do when user click the edit link the Laravel will retrieve data using id parameter

index.php

@extends('layouts.admin.master')
@extends('layouts.admin.sidebar')
{{-- @extends('layouts.admin.maincontent') --}}
{{-- @extends('layouts.user.service') --}}
@extends('layouts.admin.footer')
@section('title', 'Kaffe Mini | Admin')

@section('content')

<x-admin.dashboard.nav />
 <!-- Main Content -->
<div id="content">
    <!-- Begin Page Content -->
    <div class="container-fluid">
        <x-admin.dashboard.flash />
        <!-- Page Heading -->
        <div class="d-sm-flex align-items-center justify-content-between mb-4">
            <h1 class="h3 mb-0 text-gray-800">Ads</h1>
            {{-- <a href="#" class="d-none d-sm-inline-block btn btn-sm btn-primary shadow-sm"><i
                    class="fas fa-download fa-sm text-white-50"></i> Generate Report</a> --}}
        </div>
        
            <a href="{{route('admin.ads.create')}}" class="btn btn-success float-right font-weght bold">
                <i class="fa fa-solid fa-plus p-2"></i>Add</a>

                
                <div id="content">
                    <!-- Begin Page Content -->
                    <div class="container-fluid">
                        <!-- Page Heading -->
                        <br>
                            <div class="banner_slide">
                            @foreach($list as $lists)
                            <div class="multi-carousel-item">
                            <div class="image-parent">

                                    <a href="{{route ('admin.ads.edit', $lists->id)}}" class="btn btn-success btn-icon-split float-right m-1">
                                        <span class="icon text-white-50">
                                            <i class="fa fa-pen" style="color: #ffffff;"></i>
                                        </span>
                                    </a>
                                    <form method="POST" action="{{ route ('admin.ads.destroy', $lists->id) }}"
                                        onsubmit="return confirm('Are you sure?')" class="d-inline">
                                        @csrf
                                        @method('DELETE')
                                        <button type="submit" class="btn btn-danger btn-icon-split float-right m-1">
                                            <span class="icon text-white-30">
                                                <i class="fas fa-trash"></i>
                                            </span>
                                        </button>
                                    </form>
                            <img
                                src="{{ $lists->ads_image ? asset('storage/' . $lists->ads_image) : asset('img/error/no-image.jpg') }}"
                                class="image-parent w-100" width="150" height="150"
                            />
                               
                            </div>
                            </div>
                            <br>
                            @endforeach
                        </div>
                    </div>
                </div>
            </div>
        </div>

@endsection

Web.php



Route::middleware(['auth', 'role:admin'])->name('admin.')->prefix('/admin')->group(function() {
    Route::get('/', [AdminController::class, 'index'])->name('index');
    Route::get('/adduser/invite', [AddUserController::class, 'invite_view'])->name('invite_view');

    Route::post('/roles/{role}/permissions', [RoleController::class, 'assignPermissions'])-  >name('roles.permissions');
    Route::post('/adduser/invite', [AddUserController::class, 'invite'])->name('adduser.invite');
    
    Route::resource('/roles', RoleController::class);
    Route::resource('/permissions', PermissionController::class);
    Route::resource('/adduser', AddUserController::class);
    Route::resource('/catagories', CatagoriesAdminController::class);
    Route::resource('/products', ProductController::class);
    Route::resource('/slide', SlideController::class);
    Route::resource('/orders', OrderController::class);
    Route::resource('/ads', AdsController::class);              //Advertising page
    Route::resource('/settings', SettingsController::class);
});


AdsController.php

<?php

namespace AppHttpControllersShop;


use AppModelsCatagories;
use IlluminateHttpRequest;
use AppModelsShopOrderProduct;
use AppHttpControllersController;
use AppModelsShopAdvertising;

class AdsController extends Controller
{public function index(){

        return view('admin.ads.index', [
        'count' => OrderProduct::where('status', '=', 'paid')->count(),
        'list' => Advertising::all(),
        'catagories' => Catagories::all()
        ]);
    }

    public function create()
    {

        return view('admin.ads.create', [
        'count' => OrderProduct::where('status', '=', 'paid')->count(),
        'catagories' => Catagories::all()  
        ]);

    }

    Public function store(Request $request) {

        $validated = $request->validate([
            'list_by' => ['min:3'],
            'ads_image' => ['min:3'],
            'promoted_des',
            'catagory' => ['min:3'],
            'subject' => ['min:3'],
            'title' => ['min:3'],
            'title_color' => ['min:3'],
            'subject_color' => ['min:3']
        ]);
        if($request->hasFile('ads_image')){
            //get filename with extension
            $validated['ads_image'] = $request->file('ads_image')->store('ads_image', 'public');
        }
        Advertising::create($validated);
        // dd($validated);
        
        return to_route('admin.ads.index')->with('message', 'New ads Added');

    }

    public function edit(Advertising $adslist)
    {
        $count = OrderProduct::where('status', '=', 'paid')->count();
        $catagories = Catagories::all();
        return view('admin.ads.edit', compact('adslist', 'count', 'catagories'));
    }
    public function update(Request $request, Advertising $adslist) {

        $validated = $request->validate([

            'list_by' => ['min:3'],
            'ads_image' => ['min:3'],
            'promoted_des',
            'catagory' => ['min:3'],
            'subject' => ['min:3'],
            'title' => ['min:3'],
            'title_color' => ['min:3'],
            'subject_color' => ['min:3']

        ]);

        if($request->hasFile('ads_image')){
            //get filename with extension
            $validated['ads_image'] = $request->file('ads_image')->store('ads_image', 'public');
        }
        
        $adslist->update($validated);
        
        return to_route('admin.ads.index')->with('message', 'New Ads Updated');
    }

    public function destroy(Advertising $adslist){
    $adslist->delete();
    return to_route('admin.ads.index')->with('message', 'Advertisement Deleted');

    }
}

issue while saving multi input images to database using codeigniter php

i have a form, where there are few input fields including image input field, the image input fields allow multi upload option. now when a user clicks on add more button few of the fields including image field will get duplicated, so i save the single fields to one table and using that id i save this multiple field data in second table, i did the following code:

if (isset($_POST['addproduct'])) {
    $name = $this->input->post('name');
    $country = $this->input->post('country');
    $city = $this->input->post('city');
    $heading = $this->input->post('heading');
    $dater = $this->input->post('dater');
    $description = $this->input->post('description');

    $blog_info_data = array(
        'name' => $name,
        'country' => $country,
        'city' => $city
    );

    // Insert data into 'blog_info' table and retrieve the inserted ID
    $this->db->insert('blog', $blog_info_data);
    $blog_info_id = $this->db->insert_id();

    $ImageCount = count($_FILES['pimage']['name']);

    // Create an associative array to store image file names grouped by heading
    $imagesByHeading = array();

    for ($i = 0; $i < $ImageCount; $i++) {
        $_FILES['file']['name'] = $_FILES['pimage']['name'][$i];
        $_FILES['file']['type'] = $_FILES['pimage']['type'][$i];
        $_FILES['file']['tmp_name'] = $_FILES['pimage']['tmp_name'][$i];
        $_FILES['file']['error'] = $_FILES['pimage']['error'][$i];
        $_FILES['file']['size'] = $_FILES['pimage']['size'][$i];

        // File upload configuration
        $uploadPath = './uploads/products/';
        $config['upload_path'] = $uploadPath;
        $config['allowed_types'] = 'jpg|jpeg|png|gif';

        // Load and initialize upload library
        $this->load->library('upload', $config);
        $this->upload->initialize($config);

        // Upload file to server
        if ($this->upload->do_upload('file')) {
            // Uploaded file data
            $imageData = $this->upload->data();
            $imageCsv = $imageData['file_name']; // Store the image file name for the current row

            // Get the corresponding details for the current row
            $date_value = isset($dater[$i]) ? $dater[$i] : '';
            $heading_value = isset($heading[$i]) ? $heading[$i] : '';
            $description_value = isset($description[$i]) ? $description[$i] : '';

            // Check if the heading already exists in the associative array
            if (isset($imagesByHeading[$heading_value])) {
                // Append the image file name to the existing heading entry
                $imagesByHeading[$heading_value]['images'][] = $imageCsv;
            } else {
                // Create a new entry for the heading with an array of images
                $imagesByHeading[$heading_value] = array(
                    'dater' => $date_value,
                    'description' => $description_value,
                    'image' => array($imageCsv),
                );
            }
        } else {
            // Handle upload error here (e.g., log the error)
            // You can add error handling code here
        }
    }

    // Iterate through the associative array and insert data into 'blogdetails' table
    foreach ($imagesByHeading as $heading_value => $data) {
        // Concatenate the image file names with commas
        $imagesCsv = implode(',', $data['image']);

        $blog_details_data = array(
            'blogid' => $blog_info_id,
            'dater' => $data['dater'],
            'heading' => $heading_value,
            'image' => $imagesCsv, // Comma-separated image file names
            'description' => $data['description'],
        );

        $this->db->insert('blogdetails', $blog_details_data);
    }

    $this->session->set_flashdata("Successs", "Blog Added Successfully!");
}

here all the fields are getting saved correctly excep the images, the images for the corresponding heading/date field is saved in separate rows individually, i want it to be stored as comma seaparated values in the corresponding heading/date field, how can i accomplish this, thanks in advance

How to show in another table how many value of 1,2,3 from “kondisi” column in each cluster?

This image is the example of the dataset

So i’ve asked this to ChatGPT and another AI helper, but the result is 0.

This image is table to show what i want

So from the image about table to show what i want, column “Baik” means how many number 1 is from column “kondisi” in the dataset, same as “sedang”: 2 ; “buruk”: 3;

And this below is the code that i try to fix because the result is 0 :

<h4>Jumlah Cluster</h4>
<table class="table table-border">
  <thead>
    <th>Cluster</th>
    <th>Jumlah</th>
    <th>Baik</th>
    <th>Sedang</th>
    <th>Buruk</th>
  </thead>
  <tbody>
    <?php
    if ($this->session->userdata("kmeans_result") !== NULL) {
      $res = array();
      $kondisiCounts = array();
      foreach ($this->session->userdata("kmeans_result") as $key) {
        if (!isset($res[$key[1]])) {
          $res[$key[1]] = 1;
        } else {
          $res[$key[1]]++;
        }

        // Check if 'kondisi' key exists and access it safely
        $kondisi = $key['kondisi'] ?? 0;

        // Count Kondisi values
        $clusterId = $key[1];
        if (!isset($kondisiCounts[$clusterId])) {
          $kondisiCounts[$clusterId] = array('Baik' => 0, 'Sedang' => 0, 'Buruk' => 0);
        }
        // Increment the count based on the Kondisi value
        if ($kondisi === 1) {
          $kondisiCounts[$clusterId]['Baik']++;
        } elseif ($kondisi === 2) {
          $kondisiCounts[$clusterId]['Sedang']++;
        } elseif ($kondisi === 3) {
          $kondisiCounts[$clusterId]['Buruk']++;
        }
      }

      foreach ($res as $key => $val) {
        ?>
        <tr>
          <td><?=$key?></td>
          <td><?=$val?></td>
          <td><?=$kondisiCounts[$key]['Baik'] ?? 0?></td>
          <td><?=$kondisiCounts[$key]['Sedang'] ?? 0?></td>
          <td><?=$kondisiCounts[$key]['Buruk'] ?? 0?></td>
        </tr>
        <?php
      }
    }
    ?>
  </tbody>
</table>

The dataset is from session : $this->session->userdata(“kmeans_result”)

And this below is code to show the result and become the dataset in the first image, and i use this code for reference when i ask to AI, but their solution still give result 0 in each column :

<h4>Hasil Cluster K-Means</h4>
                <div class="table-responsive" id="export">
                  <table class="table table-border">
                    <thead>
                      <?php
                        foreach ($this->session->userdata("process_datasetindex") as $n => $v) {
                          if($n==0){
                            $obj = $v;
                          }
                          ?>
                          <th><?=$v?></th>
                          <?php
                        }
                      ?>
                      <th>Cluster</th>
                    </thead>
                    <?php
                    if($this->session->userdata("kmeans_result")!==NULL){
                      $resk = $this->session->userdata("kmeans_result");
                      aasort($resk,1);
                      foreach ($resk as $key) {
                        ?>
                        <tr>
                          <td><?=$key[0]?></td>
                          <?php
                           foreach ($this->session->userdata("process_datasetindex") as $n => $v) {
                             if($n>0){
                               $attr = array_column($this->session->userdata("process_dataset"),$v,$obj);
                               ?>
                               <td><?=$attr[$key[0]]?></td>
                               <?php
                             }

                           }
                          ?>
                          <td><?=$key[1]?></td>
                        </tr>
                        <?php
                      }
                    }
                    ?>
                  </table>