How can I apply a saved configuration

I’m working on an admin page and so far I’ve only worked on PHP and a bit of HTML. But now, I have run into a problem, what I would like to know is how I could apply this configuration automatically through HTML as shown in the following script:

<?php 

if(isset($_SESSION['userID']))
{
    $sql_result=$db->ExecuteQuery("SELECT `admin_set` FROM `users` WHERE `id`={$_SESSION['userID']}");
    if($sql_result!=false)
    {
        //exit("Ok");
        $j_settings=$sql_result->fetch_assoc()['admin_set'];
        $_SESSION['admin_set']=$j_settings;
        include_once("./classes/admin_settings.class.php");
        $settings=new AdminSettings((string)$j_settings);
        //echo '<script language="javascript" type="text/javascript" src="path/to/your/file.js"> sidebarColor('.') </script>';
    }
  }

function GetThemeKey(int $index) : string
{
    switch($index)
    {
      case 0:
        return "primary";
      case 1:
        return "dark";
      case 2:
        return "info";
      case 3:
        return "success";
      case 4:
        return "warning";
      case 5:
        return "danger";
      default:
        return "primary";
    }
}
?>
<div class="card-body pt-sm-3 pt-0">
<!-- Sidebar Backgrounds -->
<div>
  <h6 class="mb-0">Sidebar Colors</h6>

</div>
<a href="javascript:void(0)" class="switch-trigger background-color">
  <div class="badge-colors my-2 text-start">
  <span class="badge filter bg-gradient-primary<?=($settings->HighlightColor==0? ' active':'')?>" data-color="primary" onclick="sidebarColor(this)"></span>
  <span class="badge filter bg-gradient-dark<?=($settings->HighlightColor==1? ' active':'')?>" data-color="dark" onclick="sidebarColor(this)"></span>
  <span class="badge filter bg-gradient-info<?=($settings->HighlightColor==2? ' active':'')?>" data-color="info" onclick="sidebarColor(this)"></span>
  <span class="badge filter bg-gradient-success<?=($settings->HighlightColor==3? ' active':'')?>" data-color="success" onclick="sidebarColor(this)"></span>
  <span class="badge filter bg-gradient-warning<?=($settings->HighlightColor==4? ' active':'')?>" data-color="warning" onclick="sidebarColor(this)"></span>
  <span class="badge filter bg-gradient-danger<?=($settings->HighlightColor==5? ' active':'')?>" data-color="danger" onclick="sidebarColor(this)"></span>
 </div>
</a>
<!-- Sidenav Type -->
<div class="mt-3">
  <h6 class="mb-0">Sidenav Type</h6>
  <p class="text-sm">Choose between 2 different sidenav types.</p>
</div>
<div class="d-flex">
  <button class="btn bg-gradient-dark px-3 mb-2 active" data-class="bg-gradient-dark" onclick="sidebarType(this)">Dark</button>
  <button class="btn bg-gradient-dark px-3 mb-2 ms-2" data-class="bg-transparent" onclick="sidebarType(this)">Transparent</button>
  <button class="btn bg-gradient-dark px-3 mb-2 ms-2" data-class="bg-white" onclick="sidebarType(this)">White</button>
</div>
<p class="text-sm d-xl-none d-block mt-2">You can change the sidenav type just on desktop view.</p>
<!-- Navbar Fixed -->
<div class="mt-3 d-flex">
  <h6 class="mb-0">Navbar Fixed</h6>
  <div class="form-check form-switch ps-0 ms-auto my-auto">
    <input class="form-check-input mt-1 ms-auto" type="checkbox" id="navbarFixed" onclick="navbarFixed(this)">
  </div>
</div>
<hr class="horizontal dark my-3">
<div class="mt-2 d-flex">
  <h6 class="mb-0">Sidenav Mini</h6>
  <div class="form-check form-switch ps-0 ms-auto my-auto">
    <input class="form-check-input mt-1 ms-auto" type="checkbox" id="navbarMinimize" onclick="navbarMinimize(this)">
  </div>
</div>
<hr class="horizontal dark my-3">
<div class="mt-2 d-flex">
  <h6 class="mb-0">Light / Dark</h6>
  <div class="form-check form-switch ps-0 ms-auto my-auto">
    <input class="form-check-input mt-1 ms-auto" type="checkbox" id="dark-version" onclick="darkMode(this)">
  </div>
</div>

Currently, what this script does is load a sidebar on the right that is displayed when a button is pressed. Specifically, my problem is that I want it to automatically apply the saved color when this element is loaded as well as make it change color when I click on one of the options and call the sidebarColor(this) function in a JavaScript file:

Pink color image

Blue color image

But if I refresh the page this color goes back to color 0 (pink). In the tests that I am doing, I have a PHP class called Admin Settings where I am setting the color 4 (orange) by default, as you can see in the previous code, I have modified the HTML so that the color is selected in the buttons based on this new default value and when I refresh the page, this button is correctly selected. But this color is not automatically applied on the page:

Problem image

So my question is: Where and how would I have to apply the sidebarColor() function so that it is called automatically when the element loads?

sidebarColor function:

function sidebarColor(a) {
  var parent = a.parentElement.children;
  var color = a.getAttribute("data-color");

  for (var i = 0; i < parent.length; i++) {
    parent[i].classList.remove('active');
  }

  if (!a.classList.contains('active')) {
    a.classList.add('active');
  } else {
    a.classList.remove('active');
  }

  var sidebar = document.querySelector('.sidenav');
  sidebar.setAttribute("data-color", color);

  if (document.querySelector('#sidenavCard')) {
    var sidenavCard = document.querySelector('#sidenavCard');
    let sidenavCardClasses = ['card', 'card-background', 'shadow-none', 'card-background-mask-' + color];
    sidenavCard.className = '';
    sidenavCard.classList.add(...sidenavCardClasses);

    var sidenavCardIcon = document.querySelector('#sidenavCardIcon');
    let sidenavCardIconClasses = ['ni', 'ni-diamond', 'text-gradient', 'text-lg', 'top-0', 'text-' + color];
    sidenavCardIcon.className = '';
    sidenavCardIcon.classList.add(...sidenavCardIconClasses);
  }
}

how to get option value of index 3 by using array filter method in php

Array
(
    [0] => Array
        (
            [option_id] => 4638
            [option_name] => custom_plugin_chatbot_checkbox
            [option_value] => on
            [autoload] => yes
        )

    [1] => Array
        (
            [option_id] => 4443
            [option_name] => custom_plugin_chatbot_checked
            [option_value] => Checked
            [autoload] => yes
        )

    [2] => Array
        (
            [option_id] => 4502
            [option_name] => custom_plugin_chatbot_Position
            [option_value] => 
            [autoload] => yes
        )

    [3] => Array
        (
            [option_id] => 4637
            [option_name] => custom_plugin_chatbot_script
            [option_value] => <script src="//code-eu1.jivosite.com/widget/eNReHbHbwb" async></script>
            [autoload] => yes
        )

    [4] => Array
        (
            [option_id] => 4445
            [option_name] => custom_plugin_chatbot_Value
            [option_value] => 
            [autoload] => yes
        )

)

Hide an html table row if all values are ‘no’ (PHP) [closed]

I’m trying to modify a PHP template without understanding this language. I have a piece of code that adds a new row to the table with different icons depending on the ‘yes/no’ value. What I’m trying to achieve is to hide or skip entirely rows that have all ‘no’ values. I understand that I have to use a variable like “is there a yes” and loop through all values before ‘printing’ them but I find it challenging to write it in an efficient manner.

Here’s the excerpt of the code:

<?php 
if($features) {
    foreach ($features as $key => $feature){ ?>
        <tr>
            <th scope="row"><?php echo esc_html( ucwords(str_replace('packagefeature', '', str_replace('_', ' ', $key)))) ?></th>
            <?php foreach ($feature as $key => $value){ ?>
                <td>
                    <?php if ($value == 'yes')  {?>
                        <i class="far fa-check"></i>
                    <?php } else{ ?>
                        <i class="far fa-times"></i>
                    <?php } ?>
                </td>
            <?php } ?>
        </tr>
    <?php }
} ?>

I appreciate your time very much and wish you all the best!
Best regards, Max.

here’s the screenshot of the desired result
enter image description here

How to get body file content [duplicate]

Im trying to do an API Call using Laravel and php. In the body of this call, I have a binary file which is of pdf format.

My code is :

     /**
     * @param Request $request
     */
    public function transform(Request $request)
    {
        $pixUrl = env('PIX_TRANSFORM_FORMAT_URL');
        $pixKey = env('PIX_TRANSFORM_FORMAT_API_KEY');

        $file = $request->file('file');

        dd($file);

        $response = Http::withHeaders([
            'x-api-key' => $pixKey,
            'Content-Type' => 'application/pdf',
        ])
            ->attach('file', $file, 'file')
            ->post($pixUrl);
    }

Here’s my postman call :

enter image description here

But as you can see, the dump returns me a null value from the file I try to request. I do need to stay with “binary” method and not “multipart/form-data”. Do you have any idea on how to resolve this ?

Trying to access array offset on value of type int Error

I just don’t understand why I can’t access created array and display values. If I displaying variable $listing it shows ok, array looks good.

  Route::get('/', function() {
    return view('listings', [
        // $Variable - Value
        'heading' => 'Latest Listings',
        'listings' => [
            'id' => 1,
            'title' => 'Listing One',
            'description' => 'Lorem ipsum dolor sit amet consectetur adipisicing elit. Odio dolorem adipisci aliquam ducimus! Sit ipsa, voluptates ab sapiente inventore odit.'
        ],

        [
            'id' => 2,
            'title' => 'Listing Two',
            'description' => 'Lorem ipsum dolor sit amet consectetur adipisicing elit. Odio dolorem adipisci aliquam ducimus! Sit ipsa, voluptates ab sapiente inventore odit.'
        ]     
    ]);
});

In views folder listings.php get error “Trying to access array offset on value of type int”

<h1> {{ $heading }} </h1>

@if(count($listings) == 0)
    <p>No listings found.</p>
@endif

@foreach($listings as $list)
    <h2>{{ $list['title'] }}</h2>
    <p>{{ $list['description'] }}</p>
@endforeach 

Error:
Can’t access aray and display

Selecting random data from database with selectionhistory

This is my first question here, I’m sorry if my question isn’t written good enough ^^
I’m currently supposed to write a small web-app that is supposed to show so called “mantras”.

The requirements are:
1. It should always show diffrent data from database – that means that
if “Mantra1” was shown the next Mantra cant be “Mantra1” again.
2. Every “Mantra” should pop-up at some point
3. It should save the history outside of the session.
4. Multiple “Mantras” can be used by diffrent units -> that means if “Unit1” and “Unit2” both can see “Mantra1”, it should also save which unit already got the “Mantras”, so if “Unit1” got “Mantra1”, “Unit2” should still be able to get the “Mantra1” as an output.

So basically, read data from a database -> save the record that was randomly chosen from the data in a selection history of some sort -> if button is pressed get new data, but not the ones that have been shown already.
The random selection will happen inside my php code.
basic program flowchart

What I’ve tried / what my approach was:
I currently have three tables in my Database (Mantras (Fields: ID, Units (which units can see the mantra), mantra_text), Units (Fields ID, unitname) and selectionhistory (ID, mantra_id, unit_id)).
My idea was, to save the mantra/unit_id into the selectionhistory with a date, when it was selected, then delete the entrys after x days. And maybe set the x days to the amount of mantras that are available for the units.

I’ve done some research the past few days, but I didn’t find any posts with the same issue.

My question is, are there any best practices for this kind of problem, are there posts somewhere with a similar problem or does anyone have an idea how to they would solve this kind of problem?

If you need anymore information to help me, please let me know!
Thank you for your time 🙂

Upgrading php to 8

Both my valet and composer is using php 8.0
But my local says

Fatal error: Composer detected issues in your platform: Your Composer dependencies require a PHP version ">= 8.0.2". You are running 7.4.30. in /Users/admin/sites/sage10/web/app/themes/sage10/vendor/composer/platform_check.php on line 24

When I upgrade php with valet using 8.0 it gives

Deprecated: Method ReflectionParameter::getClass() is deprecated in /Users/admin/.composer/vendor/illuminate/container/Container.php

But at the end it says its using 8.0. and composer -vvv about also gives php 8.0

Is there more things to consider? I don’t understand why its saying I’m using 7.4…

Enums, Traits, Interfaces and inherit abstraction

Heyho,
so, I got the following Problem:

I have a couple of Enums, that need to implement some functions. I can abstract those functions to the point, where every Enum has the same set of functions.
Now I don’t want to copy/past the same functions all the time (seems like I need a trait).

But I’d also like to Typehint, that those functions are available within a value, without typehinting the exact Enum (looks like I need an Interface).

I’d also like to avoid the need to give every enum the same trait AND the same interface (that seems like I am looking for an abstract parent)….

well… but enums can’t inherit… But how can I still get something like this? (I’d also like to use real enums, and not a class with multiple const)

Sooo, How do I phrase it…. Help please? 😀

change content when clicking from list [closed]

I would like to consult my webpage function.
Alert Viewing System Web Page

First, using mysqli fetch_assoc(), I’m able to display a list of Alert IDs that is clickable. I want to display the content of a specific Alert (Id, time, picture, etc. saved in MySQL database) on the right side of the webpage every time I click on the ID on the left.

I was thinking of adding onclick function to the clickable ID to do the job, is it possible, or anyone has another idea of how to complete this process? Thanks!

Below is my code:

<?php
require_once('config.php');
session_start();

$uname = $_SESSION['uname'];
$sql = "SELECT * FROM users
 WHERE username = '$uname'";
$result = mysqli_query($link, $sql);
$data = $result->fetch_all(MYSQLI_ASSOC);

if (!isset($_SESSION['uname'])){
    echo "<script type='text/javascript'>alert('請先登入');
    window.location='login.php';</script>";}

    $sql2 = " SELECT * FROM coba WHERE branch = 'a'";
    $sql3 = " SELECT * FROM coba WHERE branch = 'b'";
    $sql4 = " SELECT * FROM coba WHERE branch = 'c'";
    $result2 = mysqli_query($link, $sql2);
    $result3 = mysqli_query($link, $sql3);
    $result4 = mysqli_query($link, $sql4);
?>
<!DOCTYPE html>
<html>
<head>
    <title>工地警報查看系統</title>
    <link rel="stylesheet" type="text/css" href="homepage.css">
</head>
<body>
    <div class = "header">
        <div class = "branch-name">
            <?php
                    if(str_contains($uname, 'KS1')){
                         echo"「高雄鳳山」 工地警報查看系統";
                    }
                    elseif(str_contains($uname, 'TC1')){
                         echo"「台中會展中心」 工地警報查看系統";
                    }
                    elseif(str_contains($uname, 'TC2')){
                        echo"「台中火力發電厰」 工地警報查看系統";
                   }
            ?>
        </div>
    </div>
    <div class = "background-color">
        <div class = "box-left">
        <div class = "text">ID</div>
        <?php
        if(str_contains($uname, 'KS1')){
                {
                    $count2 = mysqli_num_rows($result2);
                    if($count2 == "0")
                    {
                        $output2 = '<h2>無資料</h2>';
                    }
                    else
                    {
                        while($row2 = $result2->fetch_assoc())
                        {
                        ?>
                        <div class = "table-border">
                        <table id = "table-border"> 
                        <a href = ""><?php echo $row2['id'];?></div></br>
                        </table>
                        </div>
                        <?php
                        }
                    }
                }
            }
            //else if click on button b
            elseif(str_contains($uname, 'TC1'))
                {
                    $count3 = mysqli_num_rows($result3);
                    if($count3 == "0")
                    {
                        $output3 = '<h2>無資料</h2>';
                    }
                    else
                    {
                        while($row3 = $result3->fetch_assoc()){
                        ?>
                        <div class = "table-border">
                        <table id = "table-border"> 
                        <a href = ""><?php echo $row3['id'];?></div></br>
                        </table>
                        </div>
                        <?php
                        }
                    }
                }
            //else if click on button c
            elseif(str_contains($uname, 'TC2'))
                {
                    $count4 = mysqli_num_rows($result4);
                    if($count4 == "0"){
                        $output4 = '<h2>無資料</h2>';
                    }
                    else
                    {
                        while($row4 = $result4->fetch_assoc()){
                        ?>
                        <div class = "table-border">
                        <table id = "table-border"> 
                        <a href = ""><?php echo $row4['id'];?></div></br>
                        </table>
                        </div>
                        <?php
                        }
                    }
                }
            ?>
            <div class = "logout"><a href = "logout.php">登出</a></div>
        </div>
        <div class = "box-right">
        <a id = "id">
        <?php           
        $sql1 = "SELECT * FROM coba WHERE id = id";
        $result1 = mysqli_query($link, $sql1);
        $data1 = $result1->fetch_all(MYSQLI_ASSOC);
            foreach ($data1 as $row1)
            {
                echo  "<h3>" . "ID = ". $row1['id'] . "</h3>";
                echo  "<h3>" . "警 報 時 間 = ". $row1['time'] . "</h3>";
                echo  "<h3>" . "警 報 内 容 = ". $row1['rule'] . "</h3>";
        ?>
                <div class = "image">
                    <img src="<?php echo $row1['picture']; ?>" width = "300" height = "300" />
                </div>
        <?php
            }
        ?>
        </a>
        </div>
    </div>
</body>
</html>

how to show dynamic data in bootstrap modal within loop

So, I want to show detail data from row that I clicked. I clicked from looping data showing in table. here is the code.

$fetchall = "SELECT * FROM data";
$result = mysqli_query($conn, $fetchall);
while($row = mysqli_fetch_array($result)){
$id2 = $row['id'];
$no_1 = $row['number'];
$status_1 = $row['status'];
<td style="font-size: 10pt; width:7px;background-color:#4C724A; opacity:0.7; color:white">
<a style="background-color:#5a85dd; color:white; padding:10px; border-radius:10px; margin-top:20px; " data-toggle="modal" data-target="#popUpIA<?php echo $row['id'] ?>"></a></td>}<?php}?>

and this is my modal code.

<div class="modal fade"  id="popUpIA<?php echo $id2 ?>" tabindex="-1" role="dialog" aria-labelledby="popUpIATitle" aria-hidden="true">
                      <div class="modal-dialog modal-lg"  style="background-color: #4C724A; width:50%" role="document">
                        <div class="modal-content">
                          <div class="modal-header">
                            <h5 class="modal-title" id="popUpIATitle"></h5>
                            <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                              <span aria-hidden="true">&times;</span>
                            </button>
                          </div>
                          <div class="modal-body">
                          <!-- <table style="width:100%"> -->

the problem is, modal can only popup when i clicked the last record and only can get the last id

Laravel HTTP Client Pool Error Handling Without Calling onRejected

I’m trying to catch all possible exceptions in code below.
The question is, are there any exception types that this code does not handle?

/*
 *
 * This is just an EXAMPLE code
 *
 */
    
use AppModelsUser;
use IlluminateHttpClientPool;
use IlluminateSupportFacadesHttp;
    
$users = User::all();
    
$website = "https://www.google.com/";
Http::pool(function (Pool $pool) use ($users, $website) {
    $users->each(function ($user) use ($pool, $website) {
        $pool->retry(1)
            ->timeout(60)
            ->get($website)
            ->then(function ($response) use ($user) {
                // On Fulfilled
    
                $status = 
                    !(($response instanceof Exception || $response->getStatusCode() !== 200));
    
                $user->status = $status;
                $user->save();
            });
    });
});

I am using smarty template inside my php project its working fine on php 7.4 but not working on php 8

you can see there are many missing values in php 8 or 8.1.
how can i run this on php 8 shoud i upgrade smarty or is there some other issue with the code.
I updated the smarty library in the code but it did’nt worked at all moreover it started giving error.

Smarty Object returns this in 7.4:

TshSmarty Object
(
    [RootDir] => /home2/mjollnir/public_html/dev_mjollnirgroup/
    [TemplateDir] => /home2/mjollnir/public_html/dev_mjollnirgroup/template/
    [CompileDir] => /home2/mjollnir/public_html/dev_mjollnirgroup/compile/
    [CacheDir] => /home2/mjollnir/public_html/dev_mjollnirgroup/compile/cache/
    [IsCached] => 
    [IsCompileCheck] => 1
    [IsForceCompile] => 
    [template_dir] => /home2/mjollnir/public_html/dev_mjollnirgroup/template/
    [compile_dir] => /home2/mjollnir/public_html/dev_mjollnirgroup/compile/
    [config_dir] => configs
    [plugins_dir] => Array
        (
            [0] => plugins
        )

    [debugging] => 
    [error_reporting] => 
    [debug_tpl] => 
    [debugging_ctrl] => NONE
    [compile_check] => 1
    [force_compile] => 
    [caching] => 
    [cache_dir] => /home2/mjollnir/public_html/dev_mjollnirgroup/compile/cache/
    [cache_lifetime] => 3600
    [cache_modified_check] => 
    [php_handling] => 0
    [security] => 
  
)



and returns in PHP 8:


TshSmarty Object
(
    [template_dir] => templates
    [compile_dir] => templates_c
    [config_dir] => configs
    [plugins_dir] => Array
        (
            [0] => plugins
        )

    [_cache_include] => 
    [_cache_including] => 
    [RootDir] => 
    [TemplateDir] => 
    [CompileDir] => 
    [CacheDir] => 
    [IsCached] => 
    [IsCompileCheck] => 1
    [IsForceCompile] => 
)

validation booking room outside range?

#Code validation Booking

  $request->validate([
        "start_date" => [
            "required",  
            function ($attribute, $value, $fail) use ($request) {
                $booking = BookingTransaction::where('meeting_room_id', '=', $request->meeting_room_id)->where([
                    ["start_date", "<=", $request->input('start_date') . ' ' . $request->input('start_time')],
                    ["end_date", ">=", $request->input('start_date') . ' ' . $request->input('start_time')],
                ])
                ->orWhere([
                    ["meeting_room_id",'=',$request->meeting_room_id],
                    ["start_date", "<=", $request->input('start_date') . ' ' . $request->input('end_time')],
                    ["end_date", ">=", $request->input('start_date') . ' ' . $request->input('end_time')],
                ])
                ->first();
                if ($booking) {
                    $fail(
                        sprintf("Room meeting has already been booked. Please, try booking again outside this range.",
                            CarbonCarbon::create($booking->start_date)->format("d M Y H:i"),
                            CarbonCarbon::create($booking->end_date)->format("d M Y H:i")
                        )
                    );
                }
            },
        ],
    ]);
id start_date end_date
1 2022-10-10 11:00:00 2022-10-10 15:00:00

#problem

The code above explains the validation if the user adds a booking schedule in the time range between start_date : 2022-10-10 11:00:00 to end_date:
2022-10-10 15:00:00
, it will fail,
now I want to validate if the user makes a booking outside the range between start_date:
2022-10-10 11:00:00
until
end_date:
2022-10-10 15:00:00
, it will fail,
for example:
if the user makes a booking between:
start_date: 2022-10-10 09:00:00 to end_date: 2022-10-10 16:00:00 will fail
,
how to do above validation ?