In PHP, how to recurse through a Closure when the variable name holding the anonymous function is a variable-variable

I have a list of about 100 articles, and within each article is a list of clauses. The clauses are a list of varying levels deep.

$clauses = array(
  [
    'Fields' => ['Clause' => 'clause 1', 'Status' => 'Draft']
  ],
  [
    'Fields' => ['Clause' => 'clause 2', 'Status' => 'Draft'],
    'SubClauses' => [
      [
        'Fields' => ['Clause' => 'clause 2_a', 'Status' => 'Draft'],
        'SubClauses' => [
          [
            'Fields' => ['Clause' => 'clause 2_a_1', 'Status' => 'Draft']
          ],
          [
            'Fields' => ['Clause' => 'clause 2_a_2', 'Status' => 'Draft']
          ]
        ]
      ]
    ]
  ],
  [
    'Fields' => ['Clause' => 'clause 3', 'Status' => 'Draft']
  ]
);

echo PHP_EOL;

To create an html ordered list out of the $clauses array, I built this:

function htmlList ( $clauses, $depth = 0 ) {
  
  if ( $depth == 0 ) {
    echo '<ol type="1">';
  } elseif ( $depth == 1 ) {
    echo '<ol type="i">';
  } else {
    echo '<ol type="a">';
  }
  
  foreach ( $clauses as $key => $clause ) {
    if ( isset($clauses[$key]['SubClauses']) ) {
      echo '  <li>' . $clauses[$key]['Fields']['Clause'];
      htmlList ( $clauses[$key]['SubClauses'], ++$depth );
    } elseif ( isset($clauses[$key]['Fields']) ) {
      echo '  <li>' . $clauses[$key]['Fields']['Clause'] . '</li>';
    }
  }
  
  $depth--;
  echo '  </li>';
  echo '</ol>';
}

htmlList ( $clauses );

echo PHP_EOL;

It only builds the list for a single article. When the code loops to the next article, i get a error because the function is already defined.

I want to keep the html in the template and not put it inside the code files, so I have the function in the template where it can write the html there.

I need to make the name of the function change when the next article loops, so I converted this to a closure and assigned it to a variable. I am passing the function since I need it to recurse.

$htmlList = function ( $clauses, $depth = 0 ) use ( &$htmlList ) {
  
  if ( $depth == 0 ) {
    echo '<ol type="1">';
  } elseif ( $depth == 1 ) {
    echo '<ol type="i">';
  } else {
    echo '<ol type="a">';
  }
  
  foreach ( $clauses as $key => $clause ) {
    if ( isset($clauses[$key]['SubClauses']) ) {
      echo '  <li>' . $clauses[$key]['Fields']['Clause'];
      $htmlList ( $clauses[$key]['SubClauses'], ++$depth );
    } elseif ( isset($clauses[$key]['Fields']) ) {
      echo '  <li>' . $clauses[$key]['Fields']['Clause'] . '</li>';
    }
  }
  
  $depth--;
  echo '  </li>';
  echo '</ol>';
};

$htmlList ( $clauses );

echo PHP_EOL;

This also works for a single article, but allows the name to be changed dynamically. I then made the name of the variable that holds the name of the function dynamic.

$articles = array(
    ['Title' => 'title 1', 'Status' => 'Draft'],
    ['Title' => 'title 2', 'Status' => 'Draft'],
);

for ( $i = 0; $i < sizeof($articles); $i++ ) {
  
  echo $articles[$i]['Title'] . PHP_EOL;
  
  $htmlList = 'htmlList' . '_' . $i;
  $$htmlList = function ( $clauses, $depth = 0 ) use ( &$$htmlList ) {
    
    if ( $depth == 0 ) {
      echo '<ol type="1">';
    } elseif ( $depth == 1 ) {
      echo '<ol type="i">';
    } else {
      echo '<ol type="a">';
    }
    
    foreach ( $clauses as $key => $clause ) {
      if ( isset($clauses[$key]['SubClauses']) ) {
        echo '  <li>' . $clauses[$key]['Fields']['Clause'];
        $$htmlList ( $clauses[$key]['SubClauses'], ++$depth );
      } elseif ( isset($clauses[$key]['Fields']) ) {
        echo '  <li>' . $clauses[$key]['Fields']['Clause'] . '</li>';
      }
    }
    
    $depth--;
    echo '  </li>';
    echo '</ol>';
  };
  
  $$htmlList ( $clauses );
  
}

This is where it breaks. It does not like variably named function name inside the use() and errs at the $$ because it is a variable-variable and it only allows 1 $ and I have 2 $$ since the variable name’s value changes.

Would it be better to save the function in the main code outside the template so it doesn’t have to build anew for each article, or would it better to put the function in the template and keep html out of the main code files? All other constructs surrounding html are generally in the template files.

How can I get the clauses to convert to an html list for each article it loops through?

SQL Query returning values in phpMyAdmin but not in PHP PDO code [duplicate]

I’m working on an assignment to create a management system for a high school bus transport system. Everything has been going swimmingly until now, for some reason, I cannot access the “learner_trips” (the table where trip information for every learner is stored) table.

I’m trying to access a learner’s trip information, display said information for an admin of the system, and allow the admin to email the learner’s parent with that trip information or allow said admin to remove the learner from the table.

But all I get is this error:

Warning: Trying to access array offset on value of type bool in C:xampphtdocsstorsviewadmin_lists.php on line 146

Now I understand that the error probably means the PDO function I’m using for this is returning false. But the same query in that function works and returns what it should when I put it into phpMyAdmin with an ID.

I haven’t encountered such an error anywhere else in my code or tables.

I’ve tried changing the query in the function to use implicit joins instead of INNER JOINs, I tried casting the ID gotten through POST to integers, but nothing works. I get the same error. I’ve looked at some other questions here on SO related to my problem, but none of them address my problem.

Here’s an example of what the query should return in PHP PDO, after running in phpMyAdmin:

Example of SQL query in phpMyAdmin

My related code in index.php:

        case "send_trip_info":
            // Send email with trip info to parent
            // get input
            $l_id = filter_input(INPUT_POST, "l_id");
            
            // Get trip info and parent
            $info = getPassengerInfo($l_id);
            $parent_id = get_parent_id($l_id);
            $parent_info = get_parent_info($parent_id);
            $to_name = $parent_info["name"];
            $to = $parent_info["email"];
            $name = $learners[$l_id]["name"];
            $p1_name =  $info["p1_name"];
            $p1_time =  $info["p1_time"];
            $p2_name =  $info["p2_name"];
            $p2_time =  $info["p2_time"];

            // body
            $body = "Dear $to_name, <br><br> Here is the trip information for $name: <br><br>
                <b>Pickup Point and Time</b>: $p1_name at $p1_time<br>
                <b>Dropoff Point and Time</b>: $p2_name at $p2_time<br>
                <br>
                Kind Regards<br>
                Strive High
            ";
            $alt = "Dear $to_name, nn Here is the trip information for $name: nn
                PICKUP Point and Time: $p1_name at $p1_timen
                DROPOFF Point and Time: $p2_name at $p2_timen
                n
                Kind Regardsn
                Strive High
            ";

            send_mail("STORS Trip Info For $to_name", $body, $alt, $to, $to_name);
        break;

I’ve also received the same kind of error in the “get info and parent” section of the code above.

<!-- Passenger List (learner_trips table) -->
                 <div class="learner_section" id="passengerList">
                    <div class="mb-3 table-responsive">
                                    <!-- Passenger List table here -->
                                    <table class="table table-primary table-striped table-bordered">
                                            <thead>
                                                <tr>
                                                    <th>Learner Name</th>
                                                    <th>Pickup Point</th>
                                                    <th>Pickup Time</th>
                                                    <th>Dropoff Point</th>
                                                    <th>Dropoff Time</th>
                                                    <th colspan="2">Options</th>
                                                </tr>
                                            </thead>
                                            <tbody id="pass_list">
                                                <?php for ($i = 0; $i < count($learners); $i++): ?>
                                                    <?php if (checkLearnerPassengerStatus($learners[$i]['id'])) : ?>
                                                        <?php $info = getPassengerInfo($learners[$i]["id"]); ?>
                                                        <tr>
                                                            <td name="fullName"><?php echo $learners[$i]["name"] . " " . $learners[$i]["surname"] ?></td>
                                                            <td name="p1_point_name"><?php echo $info["p1_name"] ?></td>
                                                            <td name="p1_pickup_time"><?php echo $info["p1_time"] ?></td>
                                                            <td name="p2_point_name"><?php echo $info["p2_name"] ?></td>
                                                            <td name="p2_dropoff_time"><?php echo $info["p2_time"] ?></td>
                                                            <td>
                                                                <button class="btn btn-danger" value="<?php echo $info['id'] ?>" name="cancelPassBtn">Remove From List</button>
                                                            </td>
                                                            <td>
                                                                <form method="POST">
                                                                    <input hidden name="action" value="send_trip_info"/>
                                                                    <input hidden name="l_id" value="<?php echo $learners[$i]['id'] ?>"/>
                                                                    <button class="btn btn-success" type="submit" name="emailBtn">Email Trip To Parent</button>
                                                                </form>
                                                            </td>
                                                        </tr>
                                                    <?php endif; ?>
                                                <?php endfor; ?>
                                            </tbody>
                                    </table>

The code above is from admin_lists.php where the error appears.

Here’s my code from my PDO function:

    // Get a learner's passenger info
    function getPassengerInfo($id)
    {
        global $db;
        $query = "SELECT id, t1.point_name AS p1_name, t1.pickup_time AS p1_time, t2.point_name AS p2_name, t2.dropoff_time AS p2_time FROM learner_trips 
        INNER JOIN route_points AS t1 ON t1.point_num = learner_trips.pickup_id 
        INNER JOIN route_points AS t2 on t2.point_num = learner_trips.dropoff_id WHERE learner_id = :id";
        $statement = $db->prepare($query);
        $statement->bindValue(":id", $id);
        $result = $statement->fetch();
        $statement->closeCursor();
        return $result;
    }

My full code is available in this git repo: https://github.com/moppdev/ICT3715_STORS_PROJECT

I’m not sure what I could be doing wrong? Theoretically, everything should be firing but for some reason it just refuses to? I’m not getting any other database related errors either… This error has been driving me crazy for the past two days…

Limit only shipping states (provinces) but not billing states in WooCommerce

I have the following code which limits the provinces to Valencia (Spain) only, in WooCommerce:

add_filter( 'woocommerce_states', 'tl45r_custom_woocommerce_states' );

function tl45r_custom_woocommerce_states( $states ) {

    // Only show specific provinces (Madrid - MD and Barcelona - B) for Spain (ES)
    $states['ES'] = array(
        //'MD' => __( 'Madrid', 'woocommerce' ),
        //'B'  => __( 'Barcelona', 'woocommerce' ),
        'V'  => __( 'Valencia', 'woocommerce' ),
    );

    return $states;
}

However, I want this limitation only be applied to the shipping field but not the billing field.

How can I do this?

PHP Session Causing Page To Not Load

This is a bug seen on the production server. On dev instance the code seems to be working just fine. Infact, in multiple different AWS instances the code is running just fine.

The Bug:
On loading a specific page that’s pageA.php, the session is getting problematic. Before trying to load pageA.php all other pages are loading perfectly fine. But as soon as I load the page pageA.php, all other PHP pages stop loading. ( keeping loading for 5 min+ ) & at show HTTP 503 error.

currently pageA.php is loading a lot of values into session for quick referencing data. & is infact working just find on all other AWS instances.

I’ve tried restarting the IIS server. Again same story, all pages load fine, until I load pageA.php. Then everything stops loading with the 503 error.

Checked server machine for load, CPU at 2-5% & Memory at 10% utilization. So doesn’t seem to be any kind of heavy load on the system either.

Tried destroying & recreating session in another PHPfile.

<?php

session_start();
session_destroy();
session_start();

// Check if there are any session variables set
if (!empty($_SESSION)) {
    echo '<table border="1" cellspacing="0" cellpadding="10">';
    echo '<tr><th>Session Index</th><th>Value</th></tr>';
    
    // Loop through each session variable and print its index and value
    foreach ($_SESSION as $index => $value) {
        echo '<tr>';
        echo '<td>' . htmlspecialchars($index) . '</td>';
        echo '<td>' . htmlspecialchars(print_r($value, true)) . '</td>';
        echo '</tr>';
    }

    echo '</table>';
} else {
    echo 'No session variables are set.';
}

?>

But even this file refused to load & goes to HTTP 503.

I’ve removed the session_start() & all other related code, just tried

echo " Hello ";

Works just fine. So my diagnosis is something is wrong with session, but can’t figure out how to debug it or what the issues exactly is. Can’t share code due to confidentiality. Any help in debugging is appreciated.

LiveWire v3 Dispatch Method Does Not Show Bootstrap Modal In Laravel v11

I’m working with Laravel v11 and wanted to show a Modal on users list blade when clicking on Add New Button:

<div class="card-header">
   <div class="card-tools">
      <button type="button" wire:click="addNew">Add New</button>
   </div>
</div>

And this is AppLivewireAdminUsersListUsers Class:

class ListUsers extends Component
{
    public $users;
    public $name;
    public $email;

    public function mount()
    {
        // Fetching users from the database
        $this->users = User::all();
    }

    public function addNew()
    {
        // Trigger modal open event
        $this->dispatch('showModal');
    }

    public function save()
    {
        // Save logic
        User::create([
            'name' => $this->name,
            'email' => $this->email,
        ]);

        // Reset input fields
        $this->reset('name', 'email');

        // Close the modal after saving
        $this->dispatch('closeModal');
    }

    public function render()
    {
        return view('livewire.admin.users.list-users')->layout('layouts.app');
    }
}

But now when clicking on Modal, I get this at Console Bar and nothing appears as Modal:

capture

So what’s going wrong here? How can I show the Modal properly in this case?

Note that I’m using “livewire/livewire”: “^3.5”

And here is the script in `list-users` blade:

<script>
    document.addEventListener('livewire:load', function () {
        Livewire.on('showModal', () => {
            const modal = document.getElementById('myModal');
            if (modal) {
                modal.style.display = 'block'; // Show the modal
            }
        });

        // Close modal when the close button is clicked
        document.addEventListener('click', function (event) {
            const modal = document.getElementById('myModal');
            if (event.target.classList.contains('close')) {
                modal.style.display = 'none'; // Hide the modal
            }
        });
    });
</script>

From version 8.1 to version 8.2 start laragon has this error

From version 8.1 to version 8.2 start laragon has this error

httpd.exe - Entry point not found

Procedure entry point
Cannot find nghttp2_option_set_no_rfc9113_leading_and_trailing_ws_validation in dynamic link library C:laragonbinphpphp-8.2.24-Win32-vs16-x64

What is the cause of this error, and how can I prevent it?

Display “Free Shipping” for WooCommerce Cart Products with Zero Shipping Cost

I’m trying to display “Free Shipping” for products in the WooCommerce cart that have a shipping cost of 0. I am using Webiwork Shipping Per Product WooCommerce plugin to add per-product shipping, and I want to show this message only for those products, while leaving products with non-zero shipping charges unchanged, like this screenshot:

like this screenshot

I attempted to use the following code:

add_action('woocommerce_after_cart_item_name', 'display_free_shipping_for_cart_items', 20, 2);
function display_free_shipping_for_cart_items($cart_item, $cart_item_key) {
    $packages = WC()->shipping->get_packages();

    foreach ($packages as $package) {
        if (isset($package['contents'][$cart_item_key])) {
            $product = $package['contents'][$cart_item_key];

            if (!empty($package['rates'])) {
                $shipping_rate = reset($package['rates']);
                $shipping_cost = $shipping_rate->cost;

                if ($shipping_cost == 0) {
                    echo '<p class="product-shipping-cost">Free Shipping</p>';
                }
            }
        }
    }
}

But it seems to either show nothing or doesn’t work as expected.

Empty Server response sometimes in in Chrome

I have a strange issue on a website for a customer. He is hosting via GoDaddy.

Some context:
It is a custom WordPress site fetching content via Ajax to load into the page.

Problem statement:
When testing, I noticed some random occurrences for empty responses coming back from the server. Triggering the same request over and over, it happens that the response header is empty. This is strange as I had performed the same test seconds / minutes before.

This is the result of a successful response:

{"finishTitle":"Bourland 2","finishNumber":"VP2","highlightImage":"https://qdr.app/wp-content/uploads/2024/08/leathershandtas6-320x202-1.jpg","galleryImages":"<img src="https://qdr.app/wp-content/uploads/2024/08/leathershandtas6-320x202-1-150x150.jpg" class="selectedFinishImage" data-large-src="https://qdr.app/wp-content/uploads/2024/08/leathershandtas6-320x202-1.jpg" alt="" /><img src="https://qdr.app/wp-content/uploads/2024/08/leathershandtas3-320x202-1-150x150.jpg" data-large-src="https://qdr.app/wp-content/uploads/2024/08/leathershandtas3-320x202-1.jpg" alt="" /><img src="https://qdr.app/wp-content/uploads/2024/06/8CCL-Basement-Office-Doors-Looking-at-Egress-150x150.jpg" data-large-src="https://qdr.app/wp-content/uploads/2024/06/8CCL-Basement-Office-Doors-Looking-at-Egress-1024x681.jpg" alt="" /><img src="https://qdr.app/wp-content/uploads/2024/08/leathershandtas5-320x202-1-150x150.jpg" data-large-src="https://qdr.app/wp-content/uploads/2024/08/leathershandtas5-320x202-1.jpg" alt="" />"}

With a response header looking like this:
response header successful response

Result from an empty response:

The response itself is empty.

We have the following response headers. You can see the difference.

response header empty response

What could cause this and how can it be solved?

Prestashop import, manage and update 8000+ products and 400+ categories from CSV

I have a Prestashop installation and I have a CSV file with 8000+ products with 400+ categories in it. Each product has no variants but has like 10 images. This CSV changes everyday, it contains new products, erased products (SKU not anymore in the CSV), and several random updates of any value in it (prices, quantities, descriptions, SKU, etc).

The best solution should be whole import of the CSV each day, but looks like being impossible.

Since now I have made a PHP script that reads the CSV and outputs another CSV, that meets the Prestashop import in the admin backend. I have imported this huge CSV in steps of few hundred products.

Then I wrote another PHP script that everyday reads the original CSV and then changes some values inside the PS database (quantity, price, etc), getting the SKU as a reference. If the SKU is not present (so is a new product) it outputs another CSV with new products to import. That import has to be made manually in the PS admin > import csv.

Since now it is working fairly well, but it has many limitations, needs daily supervision and intervention, and is virtually impossible to check that all the 8000 products are really updated.

My question is, is there a better way to manage all this database? As I said, the best solution should be to rewrite all the product database each day, but I did not find any way to this solution.

I have tested the Prestashop Webservice but not working properly also for the amount of products.

(I don’t know also if Prestashop is the right solution, I was even thinking about writing a PHP product catalogue based on the original CSV and add PayPal “add to cart” functions)

Only one row showing on my php mysql select

This is my code, it’s a dashboard that shows data grabbed from mysql database. The tables in the database are correctly populated, all the data is actually there. But the page only shows the first row.

<html>
<HEAD>
    <style>
        a:link, a:visited {
            background-color: #D80D30;
            color: white;
            padding: 15px 25px;
            text-align: center;
            text-decoration: none;
            display: inline-block;
        }

        a:hover, a:active {
            background-color: red;
        }
        myTable {
            
        }
        th { 
            position: sticky; 
            top: 0; 
            background-color: white;
        }
        td {
            padding: 5px;
        }
        tr {
            border-bottom: 1px solid #ddd;          
        }
        
        tr.header, tr.hover {
            background-color: #f1f1f1;
        }
                    img.center {
                display: block;
                margin-left: 0;
                margin-right: 0;
                border: 0;
                width: 100%;
                height: 100%;
                align-content: right;
                align-self: right;
                background-color: transparent;
            }
            a.a2 {
                background-color: transparent;
                text-align: right;
                padding: 0px 0px;
                position: fixed;
                bottom: 10px;
                right:0px;
                z-index: 20;
                width: 50px;
                height: 50px;
            }
    </style>
    <script>
    function myFunction()
    {
        // Declare variables
        var input, filter, table, tr, td, i, txtValue;
        input = document.getElementById("myInput");
        filter = input.value.toUpperCase();
        table = document.getElementById("myTable");
        tr = table.getElementsByTagName("tr");

        // Loop through all table rows, and hide those who don't match the search query
        for (i = 1; i < tr.length; i++) {
            td = tr[i].getElementsByTagName("td")[0];
            if (td) {
                txtValue = td.textContent || td.innerText;
                if (txtValue.toUpperCase().indexOf(filter) > -1) {
                    tr[i].style.display = "";
                } else {
                    tr[i].style.display = "none";
                }
            }
        }
    }
    function myFunction2()
    {
        // Declare variables
        var input, filter, table, tr, td, i, txtValue;
        input = document.getElementById("myInput2");
        filter = input.value.toUpperCase();
        table = document.getElementById("myTable");
        tr = table.getElementsByTagName("tr");

        // Loop through all table rows, and hide those who don't match the search query
        for (i = 1; i < tr.length; i++) {
            td = tr[i].getElementsByTagName("td")[1];
            if (td) {
                txtValue = td.textContent || td.innerText;
                if (txtValue.toUpperCase().indexOf(filter) > -1) {
                    tr[i].style.display = "";
                } else {
                    tr[i].style.display = "none";
                }
            }
        }
    }
    function myFunction3()
    {
        // Declare variables
        var input, filter, table, tr, td, i, txtValue;
        input = document.getElementById("myInput3");
        filter = input.value.toUpperCase();
        table = document.getElementById("myTable");
        tr = table.getElementsByTagName("tr");

        // Loop through all table rows, and hide those who don't match the search query
        for (i = 1; i < tr.length; i++) {
            td = tr[i].getElementsByTagName("td")[2];
            if (td) {
                txtValue = td.textContent || td.innerText;
                if (txtValue.toUpperCase().indexOf(filter) > -1) {
                    tr[i].style.display = "";
                } else {
                    tr[i].style.display = "none";
                }
            }
        }
    }
    </script>
    <datalist id="type">
        <option value="AdapterAllianz">
        <option value="AdapterCarige">
        <option value="AdapterCedacri">
        <option value="AdapterCompass">
        <option value="AdapterEurizon">
        <option value="AdapterING">
        <option value="AdapterISP">
        <option value="Auth">
        <option value="CR296">
        <option value="DR">
        <option value="Email">
        <option value="ISP">
        <option value="Mask">
        <option value="MO">
        <option value="MT">
        <option value="MTOTP">
        <option value="MultiEmail">
        <option value="MultiMT">
        <option value="PaydoCloud">
        <option value="Push">
        <option value="WAC">
        <option value="WACIO">
        <option value="WAT">
    </datalist>
    </HEAD>
<body>
    <h1>INTEGRATION</h1>
<h2><a href="index.html">HOME</a><BR></h2>

<form action="update_int_notest.php" method="get">
    <select name="type">
        <option value="ALL" selected>ALL</option>
        <option value="AdapterAllianzListenerSEC">AdapterAllianzListenerSEC</option>
        <option value="AdapterAllianzListenerSIA">AdapterAllianzListenerSIA</option>
        <option value="AdapterCarige">AdapterCarige</option>
        <option value="AdapterCedacri">AdapterCedacri</option>
        <option value="AdapterCompass">AdapterCompass</option>
                <option value="AdapterEurizon">AdapterEurizon</option>
        <option value="AdapterING">AdapterING</option>
        <option value="AdapterISP">AdapterISP</option>
        <option value="Auth">Auth</option>
        <option value="CR296">CR296</option>
        <option value="DR">DR</option>
        <option value="Email">Email</option>
        <option value="ISP">ISP</option>
        <option value="Mask">Mask</option>
        <option value="MO">MO</option>
        <option value="MT">MT</option>
        <option value="MTOTP">MTOTP</option>
        <option value="MultiEmail">MultiEmail</option>
        <option value="MultiMT">MultiMT</option>
        <option value="PaydoCloud">PaydoCloud</option>
        <option value="Push">Push</option>
        <option value="WAC">WAC</option>
        <option value="WACIO">WACIO</option>
        <option value="WAT">WAT</option>
        <option value="ubmApi">ubmApi</option>
        <option value="ubmMT">ubmMT</option>
        <option value="ubmRejected">ubmRejected</option>
        <option value="ubmAdapters">ubmAdapters</option>
        <option value="ubmMail">ubmMail</option>
        <option value="ubmWA">ubmWA</option>
    </select>
    <br>
    <p>Select refresh type:</p>
        <input type="radio" id="incremental" name="range" value="incremental" checked>
        <label for="incremental">Incremental</label><br>
        <input type="radio" id="full" name="range" value="full">
        <label for="full">Full</label><br>
    <br>
    <input type="submit" value="Refresh Data"/>
</form>


<table id="myTable" border="3" BORDERCOLOR=#F4982B>
<thead>
    <tr >
        <th><input list="type" id="myInput" onkeyup="myFunction()" placeholder="Search for type.."></th>
        <th><input id="myInput2" onkeyup="myFunction2()" placeholder="Search for ID.."></th>
        <th><input id="myInput3" onkeyup="myFunction3()" placeholder="Search for name.." width=100%></th>
        <th align="center"><?php $date5 = date('d-m-Y',strtotime("-4 days"));print($date5); ?><br>
        <a href="fail_int_filter_new.php?date=<?php print($date5); ?>">Filter</a></th>
        <th align="center"><?php $date4 = date('d-m-Y',strtotime("-3 days"));print($date4); ?><br>
        <a href="fail_int_filter_new.php?date=<?php print($date4); ?>">Filter</a></th>
        <th align="center"><?php $date3 = date('d-m-Y',strtotime("-2 days"));print($date3); ?><br>
        <a href="fail_int_filter_new.php?date=<?php print($date3); ?>">Filter</a></th>
        <th align="center"><?php $date2 = date('d-m-Y',strtotime("-1 days"));print($date2); ?><br>
        <a href="fail_int_filter_new.php?date=<?php print($date2); ?>">Filter</a></th>
        <th align="center"><?php $date1 = date('d-m-Y');print($date1); ?><br>
        <a href="fail_int_filter_new.php?date=<?php print($date1); ?>">Filter</a></th>  
        <th align="center">Note</th>
        <th align="center">Insert</th>
        <th align="center">Delete</th>
    </tr>
</thead>
<?php
$servername = "localhost";
$username = "automation";
$password = "Kaleyra1!";
$dbname = "automation";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

$sql_tests ="SELECT DISTINCT t.ID, h.test_type, h.test_name FROM int_tmp h left join testID_1 t on h.test_name=t.Name ORDER BY `t`.`ID`, h.test_type, h.test_name  DESC";
$res_tests = $conn->query($sql_tests);
$date=date('Y-m-d',strtotime("-4 days"));
$sql_hist ="SELECT test_name, test_status, test_runtime FROM int_tmp where test_runtime > date("".$date."") order by test_runtime";
$res_hist = $conn->query($sql_hist);
$sql_bugs ="SELECT DISTINCT test_name,bug_id from bugs;";
$res_bugs = $conn->query($sql_bugs);
$sql_note="SELECT test_name,nota,insert_date from int_note ORDER BY insert_date desc";
$res_note=$conn->query($sql_note);

while ($test=$res_tests->fetch_assoc()) {
    print("<tr><td>".$test["test_type"]."</td>");
    print("<td>".$test["ID"]."</td>");
    print("<td style="text-align:left">".$test["test_name"]."</td>");
    for ($i=4;$i>=0;$i--) {
        $present=FALSE;
        while ($row = $res_hist->fetch_assoc()) {
            if ($test["test_name"]==$row["test_name"] AND date('d-m-Y',strtotime($row["test_runtime"]))==date('d-m-Y',strtotime("-".$i." days"))) {
                print("<td align="center"><img src="./img/".$row["test_status"].".png" width="30" height="30" ><br>".substr($row["test_runtime"],-8)."</td>");
                $present=TRUE;
            }
        }
        if ($present==FALSE) {
            print("<td></td>");
        }
        $res_hist->data_seek(0);
    }
    print("<td>");
    while ($bug = $res_bugs->fetch_assoc()) {
        if ($bug["test_name"]==$test["test_name"]) {
            print("<a href=https://kaleyra.atlassian.net/browse/".$bug["bug_id"].">".$bug["bug_id"]."</a><br>");
        }
    }
    $res_bugs->data_seek(0);
    while ($note = $res_note->fetch_assoc()) {
        if ($note["test_name"]==$test["test_name"]) {
            print($note["nota"]." - ".$note["insert_date"]."<br>");
        }
    }
    $res_note->data_seek(0);
    print("</td>");
    print("<td><a href="ins_int.php?type=".$test["test_type"]."&name=".$test["test_name"]."" target="new">Insert</td>");
    print("<td><a href="del_int.php?type=".$test["test_type"]."&name=".$test["test_name"]."" target="new">Delete</td>");
    print("</tr>");
}




$conn->close();
?>
</table>
<a href="#top" class="a2"><img src="img/red-arrow.png" class="center"/></a>
</body>
</html>

The tables are correctly populated, but only the first row shows. I have tried multiple solutions, but can’t come up with a fix. It worked fine until early this morning, but now I can’t get it to show all the rows.

String folder structure with all matching folders listed

I’ve been trying to do this for a few days and really I’m struggling. How do I generate all possible scanned folders from the string below and replace all possible folders in %%%ANY_DIR%%%?

$multiple_folder_scan_structure = "Customers/%%%ANY_DIR%%%/HW/%%%ANY_DIR%%%/XR7 and XR7 plus (7702 and 7703)";

The expected output should list all possible complete folder paths found within the defined structure above. With one %%%ANY_DIR%%% this is easy, but with 2 or 3, I’m completely lost as to how to accomplish this.

An example of the expected array would like something like this:

../../Customers/Morrisons/HW/SS90 Card Only (7709)/XR7 and XR7 plus (7702 and 7703)
../../Customers/Morrisons/HW/Test/XR7 and XR7 plus (7702 and 7703)
../../Customers/Sainsbury's/HW/SS90 Card Only (7709)/XR7 and XR7 plus (7702 and 7703)
../../Customers/Tesco/HW/SS90 Card Only (7709)/XR7 and XR7 plus (7702 and 7703)

I have tried to below among other codes, but it clashes as soon as I scan the first %%%ANY_DIR%%%, then the variable I use suddenly isn’t linear. I feel I should implement a dynamic loop (maybe While), but I’m clueless.
I use my “scan_dir_sorted” function here that scans any folder and puts it into an array.

      $multiple_folder_scan_structure_anydir_exp = explode('/', $multiple_folder_scan_structure);
      
      $any_dir_counter = 0;
      foreach ($multiple_folder_scan_structure_anydir_exp as $folder)  {
        if (strtoupper($folder) == "%%%ANY_DIR%%%")  {
          //echo $multiple_folder . "<br>";
          
            foreach (scan_dir_sorted($multiple_folder) as $any_dir)  {
              //echo $multiple_folder . $any_dir . "<br>";
              $any_dir_scanned_folders[$any_dir_counter][] = $any_dir;
            
            }
          $any_dir_counter++;
          $multiple_folder .= $folder . "/";
        }
        else
          $multiple_folder .= $folder . "/";
      }

Any help is appreciated.

Thanks

Empty data returned using method listDomainsTrafficStats when spam rate has no value

I have create a page to retrieve Google Postmaster data using API calls on a PHP file. The method works well and I’m getting the data that I want however I have realised that as soon as a subdomain has no data in spam rate for example, the method returns nothing despite the fact that this subdomain ($domainGoogleName) still has IP reputation or domain reputation for that specific day.

// Create Postmaster Tools service
$postmasterService = new PostmasterTools($client);
try{
$trafficStats = $postmasterService->domains_trafficStats->listDomainsTrafficStats($domainGoogleName,
                        [
                            "startDate.day" => [intval($startDay)],
                            "startDate.month" => [intval($startMonth)],
                            "startDate.year" => [intval($startYear)],
                            "endDate.day" => [intval($endDay)],
                            "endDate.month" => [intval($endMonth)],
                            "endDate.year" => [intval($endYear)],
                        ]);
if (count($trafficStats->getTrafficStats()) === 0) {
echo "NO DATA";
} else {
foreach ($trafficStats->getTrafficStats() as $stat) {
echo $stat->getDomainReputation();
echo $stat->getDkimSuccessRatio();
echo $stat->getUserReportedSpamRatio();
etc
...
}
}
                } catch (Exception $e) {
                    echo $e->getMessage();
                
                }

Would you know why Google doesn’t return anything even-though I know there is data?
Thanks

I have tried to change the date to pull the data, tried to add an if to check if there is value but my algorithm doesn’t even display “NO DATA”

Json_decode display field start chronological order

How can I arrange the date (start) in chronological order when displaying a json file with several fields?

This is the json file:

{
"0": { 
"id": 1, 
"rid": 1, 
"eventType": "Rendez-vous simple", 
"title": "CONGES PAYES", 
"description": "", 
"start": "01-01-2024 00:00:00", 
"end": "06-01-2024 00:00:00", 
"color": "#000" 
}, 
"1": { 
"id": 2, 
"rid": 2, 
"eventType": "Rendez-vous simple", 
"title": "CARGILL Za 44000 MONTOIR", 
"description": "[R\u00e9f:6201]", 
"start": "16-01-2024 08:00:00", 
"end": "16-01-2024 10:00:00", 
"color": "#CF00F4" 
}, 
"2": { 
"id": 3, 
"rid": 3, 
"eventType": "Rendez-vous simple", 
"title": "ADMINISTRATIF", 
"description": "", 
"start": "08-01-2024 00:00:00", 
"end": "13-01-2024 00:00:00", 
"color": "#FF8C00" 
} 
}

sort(), usort(), asort()?

Pagination in WordPress is not working, second page loads wrong template

I have problems with my pagination. On the first page 5 posts are correctly displayed on the correct template archive-buch.php and also the pagination button, the next page is empty and a wrong template, index.php is loaded.
The existing posts for this problem have not helped me.
I am grateful for any help.

First here my screenshots:
correct template with data

wrong template no data

Here ist my archive-buch.php

    <?php get_header(); ?>

<?php
// Anzahl der Posts pro Seite
$posts_per_page = 5;  // Anzahl der Beiträge pro Seite
$paged = ( get_query_var('paged') ) ? get_query_var('paged') : 1;  // Aktuelle Seite

/*
if ( get_query_var('paged') ) { $paged = get_query_var('paged'); }
elseif ( get_query_var('page') ) { $paged = get_query_var('page'); }
else { $paged = 1; } */


// WP_Query für den Buch-Post-Typ
$args = array(
    'post_type' => 'buch',   // Custom Post Type „buch“
    'posts_per_page' => $posts_per_page,   // Anzahl der Bücher pro Seite
    'paged' => $paged,       // Aktuelle Seite setzen
    'offset' => $posts_per_page * ($paged - 1)
);

// Neue Abfrage erstellen
$query = new WP_Query( $args );

// Debugging - Query überprüfen
/*
echo '<pre>';
print_r( $query );
echo '</pre>';
*/

if ( $query->have_posts() ) : 
    while ( $query->have_posts() ) : $query->the_post(); ?>

        <!-- Ausgabe des Buch-Titels und Inhalts -->
        <article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
            <h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>
            <div><?php the_excerpt(); // Ausgabe des Auszugs ?></div>
        </article>

    <?php endwhile; ?>

    <!-- Pagination -->
    <div class="pagination">
        <?php
        // Vorherige Seite (Link zur vorherigen Seite anzeigen)
        previous_posts_link( '« Vorherige Seite' );

        // Nächste Seite (Link zur nächsten Seite anzeigen)
        next_posts_link( 'Nächste Seite »', $query->max_num_pages );
        ?>
    </div>

<?php else : ?>
    <p>Keine Bücher gefunden.</p>
<?php endif; ?>

<?php
// Reset der Query-Daten
wp_reset_postdata();
?>

<!-- Footer -->
<footer>
    <p>&copy; <?php echo date('Y'); ?> - Alle Rechte vorbehalten.</p>
</footer>

<?php wp_footer(); ?>

And here part of my functions.php

function create_buch_post_type() {
    $args = array(
        'label'             => 'Bücher',
        'public'            => true,
        'has_archive'       => true, // Stellt sicher, dass ein Archiv vorhanden ist
        'rewrite'           => array( 'slug' => 'buecher' ),  // Rewrite-URL korrekt setzen
        'supports'          => array( 'title', 'editor', 'excerpt' ),
    );
    register_post_type( 'buch', $args );
}
add_action( 'init', 'create_buch_post_type' );

Any help is appreciated

Codeigniter 3 edit and delete user details from database by admin role

I am creating a web application using codeigniter 3. I have created the database and views and models for user and for admin also now i stucked at some point where i need to give permission to admin so that he can delete a user information or can update it. How to do this.

Here is my edit controller view and model code respectively

//#### User Edit Controller

load->model(‘User_model’); // Correct model loading
$this->load->helper(‘url’); // Load the URL helper
$this->load->library(‘form_validation’); // Load form validation library
}

// Display the edit form with user details
public function edit_user($userid) {
$data[‘user’] = $this->User_model->get_user_by_userid($userid); // Get user data based on userid
if (!$data[‘user’]) {
show_404(); // Show 404 if user not found
}
$this->load->view(‘update_user’, $data); // Load view with user data
}

// Update user details in the database
public function update_user($userid) {
// Set form validation rules
$this->form_validation->set_rules(‘userid’, ‘User ID’, ‘required’);
$this->form_validation->set_rules(‘role’, ‘Role’, ‘required’);
$this->form_validation->set_rules(‘password’, ‘Password’, ‘required’);

if ($this->form_validation->run() == FALSE) {
// Validation failed, reload the edit form with existing data
$this->edit_user($userid);
} else {
// Prepare user data for update
$user_data = array(
‘userid’ => $this->input->post(‘userid’),
‘role’ => $this->input->post(‘role’),
‘password’ => $this->input->post(‘password’)
);

// Update user in the database
$this->User_model->update_user_by_userid($userid, $user_data);

// Redirect back to the edit page for further updates
redirect(‘UserEditController/edit_user/’ . $userid);
}
}

}

//#### User Edit View

Edit User Information

userid); ?>” method=”POST”>

    <!-- User ID (Disabled, as it shouldn't be editable) -->
    <div class="form-group">
        <label for="userid">User ID</label>
        <input type="text" class="form-control" id="userid" name="userid" value="<?php echo set_value('userid', $user->userid); ?>" readonly>
    </div>

    <!-- Role -->
    <div class="form-group">
        <label for="role">Role</label>
        <select class="form-control" id="role" name="role" required>
            <option value="">Select Role</option>
            <option value="admin" <?php echo set_select('role', 'admin', ($user->role == 'admin')); ?>>ADMIN</option>
            <option value="user" <?php echo set_select('role', 'user', ($user->role == 'user')); ?>>USER</option>
        </select>
        <?php echo form_error('role'); ?>
    </div>

    <!-- Password -->
    <div class="form-group">
        <label for="password">Password</label>
        <input type="password" class="form-control" id="password" name="password" required>
        <?php echo form_error('password'); ?>
    </div>
    
    <!-- Submit Button -->
    <div class="form-group">
        <button type="submit" class="btn btn-success">
            <i class="fas fa-save"></i> Update User
        </button>
    </div>
</form>

//#### User Edit Model

db->insert(‘users’, $data);

$data = $this->input->post();

}

public function get_user_by_userid($userid) {
$this->db->where(‘userid’, $userid);
$query = $this->db->get(‘users’); // Replace ‘users’ with your table name
return $query->row(); // Return a single row
}

// Update user details
public function update_user_by_userid($userid, $user_data) {
$this->db->where(‘userid’, $userid);
return $this->db->update(‘users’, $user_data); // Replace ‘users’ with your table name
}
}
?>

Ib have placed it in the user model