Getting correct run order in a while($x = $y->fetch_assoc()){} loop

Just started playing around with php and mysql, loading small images from a database and stumbled across this little problem. Can anyone help me get the right display order and explain why what I’m doing doesnt work? What I want is this:

Database contains x items.
<img 1>
Text under image.
<img 2>
Text under image.

But with this code:

if ($result->num_rows > 0) {
echo "Database contains ".$result->num_rows." items.";
// output data of each row
while($row = $result->fetch_assoc()) {

  $src = "data: ".$row['jpgornot'].";base64,".$row['pic'];

  echo "<img src = '" . $src . "'><br><br>";
  echo "Text under image.";
}

}

I get:

<img 1>
Database contains x items.
<img 2>
Text under image.
Text under image.

How to display a new table (2) after click on row table (1) for view details

I have a table with a list of players, by clicking on the players row I would like to display a table below with the player’s details. I can do it but when I click the table with the players… display twice player’s table and below the table with the details. Where is the error? Thanks

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

          $q_classifica = "SELECT * FROM giocatori ORDER BY punti DESC";
          if($r_classifica = $conn->query($q_classifica))
          {
              $indice=1;

              echo '<div class="box-class1 roboto-bold">
              <table style="width: 380px; height: 60px;" border="0" cellpadding="2" cellspacing="2" class="scrolldown prova">
              <thead><tr>
              <th style="width: 60px"></th>
              <th style="width: 205px"></th>
              <th style="width: 86px"></th>
              <th style="width: 29px"></th>
              </tr></thead><tbody>';
              
              while ($row1 = $r_classifica->fetch_array())
              {
                  echo '
                  <tr class="mia" id="' . $row1['ID'] . '">
                  <td style="width: 60px"><a href="https://wa.me/' . $row1['cell'] . '?text=Ciao...%20vorrei sfidarti!!!%20al%20torneo"><img style="width: 17px; height: 19px;" alt="ball" src="ball.png"></a>   ' . $indice . '</td>
                  <td style="width: 205px">' . $row1['nome'] . '</td>
                  <td style="width: 86px">' . $row1['punti'] . '</td>';
            
                      $infortunio = $row1['infortunio'];
                      if($infortunio==si){echo '<td style="width: 29px"><img style="width: 30px; height: 22px;" alt="infortunato" src="ambulanza.png"></td></tr>';}
                      else{
                      echo '<td></td></tr>';
                          }
                      $indice++;
              }
              echo "</tbody></table></div>";

          }else{
              echo "Errore impossibile eseguire la query $q_classifica. " . $conn->error;
              }
          ?>

          <script>
          $(document).ready(function(){
              $('.mia').click(function(){
                      id_player = $(this).attr('id')
                      $.ajax({url: "home.php",
                      method:'post',
                      data:{player_id:id_player},
                    success: function(result){
                      $(".modbody").html(result);
          }});
                // $('#myModal').modal("show");

              })
          })
          </script>

          <div class="modbody">
          <?php

          if(isset($_POST["player_id"]))
          {

          $output = '';


          $a_giocatore = "SELECT nome FROM giocatori WHERE giocatori.id = '".$_POST["player_id"]."'";
          $result = $conn->query($a_giocatore);
          while ($row = mysqli_fetch_assoc($result))
              {
                  $giocatore= $row['nome'];
              } 

          $output .= '
          <H2><div style="text-align: center;" class="roboto-black-italic box-giocatore1">' . $giocatore . '</H2></div>';


          $q_partita = "SELECT * FROM partite WHERE (giocatore_1 = '$giocatore' OR giocatore_2 = '$giocatore') AND (vittoria = '$giocatore') AND (punteggio IS NOT NULL) ORDER BY data DESC";
          if($r_partita = $conn->query($q_partita))
              {
                  $output .= '
                  <table style="text-align: center;" border="0" cellpadding="2" cellspacing="1" class="vinte">
                      <thead>
                          <tr>
                              <th style="vertical-align: top; width: 105px;"><br></th>
                              <th style="vertical-align: top; width: 105px;"><img alt="up" src="vi.png"><br></th>
                              <th style="vertical-align: top; width: 70px;"><br></th>
                              <th style="vertical-align: top; width: 70px;"><br></th>
                          </tr>
                      </thead>';
              
                  while ($row1 = $r_partita->fetch_array())
                  {
                      $data = $row1['data'];
                      $timestamp_data = strtotime($data); // converte data in formato leggibile a video, cercare modo di mettere nomi in ITA
                      $formato = 'j M Y'; 
                      $resultd = date($formato, $timestamp_data); // converte data in formato leggibile a video, cercare modo di mettere nomi in ITA
                      $output .= '
                      <tbody>
                          <tr>
                              <td class="roboto-regular-italic"><font size="1">' . $row1['giocatore_1'] . '</font></td>
                              <td class="roboto-regular-italic"><font size="1">' . $row1['giocatore_2'] . '</font></td>
                              <td class="roboto-regular-italic"><font size="1">' . $row1['punteggio'] . '</font></td>
                              <td class="roboto-regular-italic"><font size="1">' . $resultd . '</font></td>
                          </tr>';
                  }
                  $output .= '
                      </tbody>
                  </table>';
              }


          $q_partita2 = "SELECT * FROM partite WHERE (giocatore_1 = '$giocatore' OR giocatore_2 = '$giocatore') AND (sconfitta = '$giocatore') AND (punteggio IS NOT NULL) ORDER BY data DESC";
          if($r_partita2 = $conn->query($q_partita2))
              {
                  $output .= '
                  <table style="text-align: center;" border="0" cellpadding="2" cellspacing="1" class="perse">
                      <thead>
                          <tr>
                              <th style="vertical-align: top; width: 105px;"><br></th>
                              <th style="vertical-align: top; width: 105px;"><img alt="up" src="sc.png"><br></th>
                              <th style="vertical-align: top; width: 70px;"><br></th>
                              <th style="vertical-align: top; width: 70px;"><br></th>
                          </tr>
                      </thead>';
                      
                  while ($row1 = $r_partita2->fetch_array())
                  {
                      $data2 = $row1['data'];
                      $timestamp_data2 = strtotime($data2); // converte data in formato leggibile a video, cercare modo di mettere nomi in ITA
                      $formato2 = 'j M Y'; 
                      $result2 = date($formato2, $timestamp_data2); // converte data in formato leggibile a video, cercare modo di mettere nomi in ITA
                      $output .= '
                      <tbody>
                          <tr>
                              <td class="roboto-regular-italic"><font size="1">' . $row1['giocatore_1'] . '</font></td>
                              <td class="roboto-regular-italic"><font size="1">' . $row1['giocatore_2'] . '</font></td>
                              <td class="roboto-regular-italic"><font size="1">' . $row1['punteggio'] . '</font></td>
                              <td class="roboto-regular-italic"><font size="1">' . $result2 . '</font></td>
                          </tr> ';
                  }
                  $output .= '
                      </tbody>
                  </table>';
              }

          echo $output;
          unset ($giocatore);

          }
          ?>
          </div>

I tried to send the url via post in the same page but the first table appears twice. I would like to do this process without reloading the page, thanks

BEFORE CLICK

AFTER CLICK

Dynamic pagination using JavaScript Datatable is not working? [closed]

Upon reinitializing warning is shown and existing pagination is missing, current pagination show the default 50 records only.

I have alternatively implemented another pagination which is working,but I require the in built javascript pagination.

Below is my HTML code-

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Data</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
    <script src="https://code.jquery.com/jquery-3.7.1.js"></script>
    

<!-- Styles -->
<link href="assets/css/style.css" rel="stylesheet">
<style>
    #pagination a {
        padding: 5px;
        text-decoration: none;
        color: #007bff;
    }
    #pagination .current {
        padding: 5px;
        font-weight: bold;
        color: #000;
    }
    #loading-message {
        text-align: center;
        display: none;
    }
</style>
 <title> Dashboard</title>
<div class="content-wrap">
    <div class="container mt-5">
        <h5>Journal Subscriptions and Revenue</h5>
        <table id="bootstrap-data-table-export" class="table table-striped table-bordered">
            <thead>
                <tr>
                    <th>Name</th>
                    <th>Cust_No_</th>
                    <th>Journal_ID</th>
                    <th>Content_Year</th>
                    <th>Subject</th>
                    <th>Journal_Title</th>                
                    <th>Type_of_Subscription</th>
                </tr>
            </thead>
            <tbody id="table-body">
                <!-- Data will be loaded here -->
                <?php  foreach ($results as $row): ?>
        <tr>
            <td><?= htmlspecialchars($row['Name']); ?></td>
            <td><?= htmlspecialchars($row['Cust_No_']); ?></td>
            <td><?= htmlspecialchars($row['Journal_ID']); ?></td>
            <td><?= htmlspecialchars($row['Content_Year']); ?></td>
            <td><?= htmlspecialchars($row['Subject']); ?></td>
            <td><?= htmlspecialchars($row['Journal_Title']); ?></td> 
            <td><?= htmlspecialchars($row['Type_of_Subscription']); ?></td>
                                                                
        </tr>
        <?php endforeach; ?>
            </tbody>
        </table>

        <!-- Pagination Links -->
        <div id="pagination">
            <!-- Pagination links will be loaded here -->     
            <?php if ($page > 1): ?>
                <a href="?page=<?= $page - 1; ?>">Previous</a>
            <?php endif; ?>

            <span>Page <?= $page; ?> of <?= $totalPages; ?></span>

            <?php if ($page < $totalPages): ?>
                <a href="?page=<?= $page + 1; ?>">Next</a>
            <?php endif; ?>                  
        </div>
    </div>
    <div id="loading-message">
        <p>Loading more data...</p>
    </div>
</div>
<script>
    let currentPage = 1;
    let totalPages = 1;
    let loading = false;

    function loadData(page) {
        $.ajax({
            url: 'journal_data_19.php',
            type: 'GET',
            data: { page: page },
            dataType: 'json',
            success: function(data) {
                if (data.error) {
                    alert('Error: ' + data.error);
                    return;
                }
                totalPages = data.totalPages;
                currentPage = data.currentPage;

                const tableBody = $('#table-body');
                tableBody.empty(); // Clear existing data

                data.results.forEach(row => {
                    tableBody.append(
                        `<tr>
                            <td>${row.Name}</td>
                            <td>${row.Cust_No_}</td>
                            <td>${row.Journal_ID}</td>
                            <td>${row.Content_Year}</td>
                            <td>${row.Subject}</td>
                            <td>${row.Journal_Title}</td>
                            <td>${row.Type_of_Subscription}</td>
                        </tr>`
                    );
                });

                updatePagination();
            },
            error: function(xhr, status, error) {
                console.error('AJAX Error:', status, error);
            }
        });
    }

    function updatePagination() {
        const paginationElement = document.getElementById('pagination');
        if (paginationElement) {
            let paginationHtml = '';

            // Previous button
            if (currentPage > 1) {
                paginationHtml += `<a href="#" onclick="loadData(${currentPage - 1}); return false;">Previous</a> `;
            }

            // Page numbers
            for (let i = 1; i <= totalPages; i++) {
                if (i === currentPage) {
                    paginationHtml += `<span class="current">${i}</span> `;
                } else {
                    paginationHtml += `<a href="#" onclick="loadData(${i}); return false;">${i}</a> `;
                }
            }

            // Next button
            if (currentPage < totalPages) {
                paginationHtml += `<a href="#" onclick="loadData(${currentPage + 1}); return false;">Next</a>`;
            }

            paginationElement.innerHTML = paginationHtml;
        } else {
            console.error('Pagination element not found');
        }
    }

    function loadMoreData(page) {
        if (loading) return; // Prevent multiple requests at the same time
        loading = true;
        $('#loading-message').show();

        $.ajax({
            url: 'journal_data_19.php',
            type: 'GET',
            data: { page: page },
            dataType: 'json',
            success: function(data) {
                if (data.error) {
                    alert('Error: ' + data.error);
                    return;
                }
                totalPages = data.totalPages;
                currentPage = data.currentPage;

                const tableBody = $('#table-body');

                // Append the fetched rows to the table
                data.results.forEach(row => {
                    tableBody.append(
                        `<tr>
                            <td>${row.Name}</td>
                            <td>${row.Cust_No_}</td>
                            <td>${row.Journal_ID}</td>
                            <td>${row.Content_Year}</td>
                            <td>${row.Subject}</td>
                            <td>${row.Journal_Title}</td>
                            <td>${row.Type_of_Subscription}</td>
                        </tr>`
                    );
                });

                loading = false;
                $('#loading-message').hide();
            },
            error: function(xhr, status, error) {
                console.error('AJAX Error:', status, error);
                loading = false;
                $('#loading-message').hide();
            }
        });
    }

    $(document).ready(function() {
        loadData(currentPage); // Initial load

        // Event listener for scrolling
        $(window).scroll(function() {
            if ($(window).scrollTop() + $(window).height() >= $(document).height() - 100 && !loading && currentPage < totalPages) {
                loadMoreData(++currentPage);
            }
        });
    });




    //JAVASCRIPT PAGINATION SECTION---------------------$(document).ready(function() {
    $('#bootstrap-data-table-export').DataTable({
        "processing": true,
        "serverSide": true,
        "ajax": {
            "url": "journal_data_19.php",
            "type": "GET",
            "dataSrc": function (json) {
                // Check if json.data exists and contains data
                if (json.data && json.data.length > 0) {
                    return json.data;
                } else {
                    console.error('No data found or incorrect format');
                    return [];
                }
            },
            "error": function (xhr, error, thrown) {
                console.error('An error occurred while fetching data:', error);
            }
        },
        "pageLength": 50,
        "lengthMenu": [[10, 25, 50, 100, -1], [10, 25, 50, 100, "All"]],
        "columns": [
            { "data": "Name" },
            { "data": "Cust_No_" },
            { "data": "Journal_ID" },
            { "data": "Content_Year" },
            { "data": "Type_of_Subscription" },
            { "data": "Journal_Title" },
            { "data": "Subject" }
        ],
        "paging": true,
        "searching": true,
        "ordering": true,
        "dom": 'Bfrtip',
        "buttons": ['copy', 'csv', 'excel', 'pdf', 'print'],
        "scrollY": "500px",
        "scrollCollapse": true,
        "responsive": true
    });
});

    </script>
<script src="assets/js/lib/jquery.nanoscroller.min.js"></script>
<!-- nano scroller -->
<script src="assets/js/lib/menubar/sidebar.js"></script>
<script src="assets/js/lib/preloader/pace.min.js"></script>
<!-- sidebar -->

<!-- bootstrap -->

<script src="assets/js/scripts.js"></script>
<!-- scripit init-->
<script src="assets/js/lib/data-table/datatables.min.js"></script>
<!-- <script src="assets/js/lib/data-table/buttons.dataTables.min.js"></script> -->
<script src="assets/js/lib/data-table/dataTables.buttons.min.js"></script>
<script src="assets/js/lib/data-table/buttons.flash.min.js"></script>
<script src="assets/js/lib/data-table/jszip.min.js"></script>
<script src="assets/js/lib/data-table/pdfmake.min.js"></script>
<script src="assets/js/lib/data-table/vfs_fonts.js"></script>
<script src="assets/js/lib/data-table/buttons.html5.min.js"></script>
<script src="assets/js/lib/data-table/buttons.print.min.js"></script>
<script src="assets/js/lib/data-table/datatables-init.js"></script>

This is my PHP code-

<?php
session_start();
ob_start(); // Start output buffering

if (!isset($_SESSION['loggedin'])) {
    header('Location: index.html');
    exit;
}

ini_set('max_execution_time', 0); // No time limit

$DATABASE_HOST = 'localhost';
$DATABASE_USER = 'root';
$DATABASE_PASS = '';
$DATABASE_NAME = 'destination_db';

// Number of records to display per page
$limit = 50;

// Get the current page number from the AJAX request
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
if ($page < 1) $page = 1; // Ensure page number is at least 1

// Calculate the offset for the SQL query
$offset = ($page - 1) * $limit;

// Parameters from DataTables
$start = $_GET['start'];
$length = $_GET['length'];
$searchValue = $_GET['search']['value']; // For search filtering

try {
    $pdo = new PDO("mysql:host=$DATABASE_HOST;dbname=$DATABASE_NAME;charset=utf8", $DATABASE_USER, $DATABASE_PASS);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    // Get the total number of records
    $totalStmt = $pdo->query('SELECT COUNT(*) FROM journal_subscription js 
                              JOIN journal_revenue jr 
                              ON js.Cust_No_ = jr.Ship_to_no_ 
                              AND js.Type_of_Subscription = jr.Type_of_Sales 
                              AND js.Content_Year = jr.Content_Year 
                              AND js.Journal_ID = jr.Journal_ID');
    $totalRows = $totalStmt->fetchColumn();
    $totalPages = ceil($totalRows / $limit);

    // Prepare the SQL query with LIMIT and OFFSET
    $stmt = $pdo->prepare('SELECT js.Cust_No_, js.Name, js.Journal_ID, js.Content_Year, js.Type_of_Subscription, jr.Subject, jr.Journal_Title
FROM journal_subscription js
JOIN journal_revenue jr
ON js.Cust_No_ = jr.Ship_to_no_
AND js.Type_of_Subscription = jr.Type_of_Sales
AND js.Content_Year = jr.Content_Year
AND js.Journal_ID = jr.Journal_ID
LIMIT :limit OFFSET :offset');
    
    // Bind parameters
    $stmt->bindParam(':limit', $limit, PDO::PARAM_INT);
    $stmt->bindParam(':offset', $offset, PDO::PARAM_INT);
    
    // Execute query
    $stmt->execute();
    
    // Fetch results
    $results = $stmt->fetchAll(PDO::FETCH_ASSOC);

    // Return JSON response
    echo json_encode([
        'results' => $results,
        'totalPages' => $totalPages,
        'currentPage' => $page
    ], JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT);
   
} catch (PDOException $e) {
    header('Content-Type: application/json');
    echo json_encode(['error' => $e->getMessage()]);
}
ob_end_clean(); // End output buffering and clean output
?>

Output

Can’t get current session’s database row on Laravel

I am trying to store the user’s geolocation information in an extra column on sessions table.
I use Fortify for authentication.
I created an extra column on sessions table for that.
migration:

public function up(): void
    {
        Schema::table('sessions', function (Blueprint $table) {
            $table->json('geolocation')->after('user_agent')->nullable();
        });
    }

Then I created a Session model which accesses the session table:

<?php
namespace AppModels;

use IlluminateDatabaseEloquentFactoriesHasFactory;
use IlluminateDatabaseEloquentModel;

class Session extends Model
{
    use HasFactory;

    protected $casts = [
        'id' => 'string',
        'user_agent' => 'collection',
        'geolocation' => 'collection'
    ];

    protected $fillable = [
      'geolocation',
      'created_at'
    ];
}

I created a listener for successfull login event. In the handle method, I try to get the session id to match the session with the row on the database. However session()->id() or session()->getId() return a different value which does not exist in the sessions table.

The question is;
What should I do in order to be able to update the active session’s database column?
What alternative approach might be tried?

I try to match the user’s active session with the row on the sessions table and update a column of it.

How to correctly configure PHP/Appache to self-host a Kanban server?

i am having issues with setting up a Vhost hosting Kanboard

It is the first time i use shell, php and apache. I wanted to install ‘Kanboard’ on MacOS Sonomoa to use it for a personnal purpose. I want to be able to access it from a browser at the adress : “kanboard.local” without having to do anything in the terminal when starting my computer.

I was not able to connect to my virtual host.

I did the following :

  • Installed Homebrew with the .pkg from their site

  • Installed php with homebrew

  • Installed MySQL and SQLite with homebrew

  • Installed HTTPD/Apache with homebrew

  • Downloaded the Kanboard master.zip from GitHub and unzipped it

Then :

I went to the HTTPD configuration file (httpd.conf) and added a line to load the php module:

LoadModule php_module lib/httpd/modules/libphp.so

I’ve checked which Directory has been declared, I’ve put : Require granted all on this directory ( …./var/www )

I added the line:

DirectoryIndex index.php index.html 

on the advice of ChatGPT

In the declared directory, I created an ‘html’ folder in which I put the kanboard folder I had unzipped Then, I went to my hosts database (/etc/hosts) and added the line:

127.0.0.0.1 kanboard.local

Finally, I went to the virtual hosts configuration file ( …/etc/extra/httpd-vhosts.conf) And I configured a virtual host like this:

Listen 8080 
<VirtualHost *:8080> 
DocumentRoot ‘/usr/local/var/www/html/kanboard’ 
ServerName kanboard.local
<Directory ‘/usr/local/var/www/html/kanboard’> 
Options Indexes FollowSymLinks MultiViews 
AllowOverride All 
Require all granted 
</Directory> 

I started php then httpd, then restarted them. I checked the ‘localhost:8080’ page it works correctly. I can use this page to browse kanboard files but the application itself is not built at all. When I try to connect to ‘kanboard.local’, I get a message “connection failed”. Can you help me / do you have any idea what is missing or causing the problem?

Adding a new column on ‘customers’ tab on Restrict Content Pro – Agree terms

I am using Restrict Content Pro and I am trying to introduce a new column to my customers table on the WordPress dashboard.

I want the column to be named something like ‘Agreed Terms’ and for each customer it should output the result of whether that customer agreed to terms which I think is currently either ‘none’ or the date in which the user signed up.

The agree to terms is in reference to whether the user accepts email communication and it isn’t required to tick.

Does anybody know how to do this? Thanks.

I have managed to get to the point of actually adding the column, however, I have been unable to pull any of the content through. I have looked online at the documentation but wasn’t able to find any kind of function or hook that allows me to get the result of the terms agreed.

This is the code I have come up with so far

function ag_rcp_customers_list_table_columns( $columns ) 
{
  $key = 'terms'; // All lowercase, no spaces. Your unique ID for your column.
  $name = __( 'Agree Terms', 'rcp' ); // Label to be displayed on the column header. Spaces are okay.
  $columns[ $key ] = $name;

  return $columns;
}

add_filter( 'rcp_customers_list_table_columns', 'ag_rcp_customers_list_table_columns' );

function ag_rcp_customers_list_table_column_company( $value, $customer ) 
{
  $terms = rcp_get_membership_meta( $customer->get_id(), 'agree-terms', true );
  
  return $terms;
}

add_filter( 'rcp_customer_list_table_column_company', 'ag_rcp_customers_list_table_column_company', 10, 2 );

This code was taken from the documentation from restrict content pro but applied to memberships. I have tried to tailor it towards customers instead.

documentation is here: documentation

Custom PHP settings PHP-FPM best practice [closed]

I am setting up a LEMP server (Ubuntu/Nginx/PHP) with PHP-FPM, and I was wondering what is the best practice for modifying global PHP settings? There seems to be a few options:

  1. Edit /etc/php/8.3/fpm/php.ini directly.
  2. Edit /etc/php/8.3/fpm/php-fpm.conf directly.
  3. Edit /etc/php/8.3/fpm/pool.d/www.conf directly (although this is normally per site files).
  4. Create a file /etc/php/8.3/fpm/conf.d/GLOBAL.ini.

I did some research, but couldn’t find any useful suggestions. I am guessing it’s not that important, but surely there are some strong opinions? I am inclined to use the last option #4, because that seems the most tidy. Thanks for suggestions.

Laravel 11 API: Always got unauthenticated message

I am using Laravel 11 for API with sanctum for authorization. Login works fine but logout always get unauthenticated with Http Status 401.

How to solve this problem and return HTTP status 200 as it suppose to do?

Here are my code and Postman’s API request

AuthController

    public function logout(Request $request)
    {
        $request->user()->currentAccessToken()->delete();

        return response()->json([
            'message' => 'Logged out successfully',
        ],200);
    }

routes/api.php

Route::post('/register', [AuthController::class, 'register']);
Route::post('/login', [AuthController::class, 'login']);
Route::middleware('auth:sanctum')->group(function () {
    Route::post('/logout', [AuthController::class, 'logout']);
});

Postman

{
    "name": "Logout",
    "request": {
        "method": "POST",
        "header": [
            {
                "key": "Authorization",
                "value": "Bearer {{access_token}}"
            },
            {
                "key": "Content-Type",
                "value": "application/json"
            },
            {
                "key": "Accept",
                "value": "application/json",
                "type": "text"
            }
        ],
        "url": {
            "raw": "{{base_url}}/api/logout",
            "host": [
                "{{base_url}}"
            ],
            "path": [
                "api",
                "logout"
            ]
        }
    },
    "response": []
},

Thanks in advance.

I tried adding gaurds but npt working
config/auth.php

    'guards' => [
        'web' => [
            'driver' => 'session',
            'provider' => 'users',
        ],
        'api' => [
            'driver' => 'sanctum',
            'provider' => 'users',
        ],
    ],

Date Format with PHP using Datetime

I have two dates I need to show it in format

29th and 30th November 2024
or
28th to 30th November 2024
or 
28th October to 30th November 2024
or
30th November and 1st December2024

What I tried so for is the code below.

                $date1 = new DateTime('2024-09-29');
                $month1 = $date1->format('m');
                $date2 = new DateTime('2024-09-30');
                $month2 = $date2->format('m');
                $interval = $date1->diff($date2);
                if($month1 == $month2){
                    if($interval->days == 1){
                        $result_date = getDayWithSuffix($date1);
                        $result_date .= ' and ';
                        $result_date .= getDayWithSuffix($date2);
                        $result_date .= ' '.$date1->format('F');
                        $result_date .= ' '.$date1->format('Y');
                    } else {
                        $result_date = getDayWithSuffix($date1);
                        $result_date .= ' to ';
                        $result_date .= getDayWithSuffix($date2);
                        $result_date .= ' '.$date1->format('F');
                        $result_date .= ' '.$date1->format('Y');
                    }
                } else {
                    if($interval->days == 1){
                        $result_date = getDayWithSuffix($date1);
                        $result_date .= ' '.$date1->format('F');
                        $result_date .= ' and ';
                        $result_date .= getDayWithSuffix($date2);
                        $result_date .= ' '.$date2->format('F');
                        $result_date .= ' '.$date1->format('Y');
                    } else {
                        $result_date = getDayWithSuffix($date1);
                        $result_date .= ' '.$date1->format('F');
                        $result_date .= ' to ';
                        $result_date .= getDayWithSuffix($date2);
                        $result_date .= ' '.$date2->format('F');
                        $result_date .= ' '.$date1->format('Y');
                    }
                }

Is there a better way to achieve this?

php password and user doesn’t after a new post call [closed]

I created a simple log-in form in php to access an archive with user and password (encrypted in MD5 without hash or salt).
I then decided to insert a filter in the archive page (to filter only results of a specific date).
When I run the filter the page no longer finds the user and password pair and redirects me to the login page.
The file is Archivio.php

Code without filter:

<?php
$utente = $_POST["Utente"];
$password = $_POST["Password"];
$password = md5($password);

$id=
$sql=mysqli_query($mysqli, "select * from Utenti_Archivio where Utente='".$utente."' and          Password='".$password."'");
    if (mysqli_num_rows($sql) == 1){
    }
    else{
        header( "Location: Login.html" );
        die;
    }

$querySQL = mysqli_query($mysqli, "select Nome,Cognome,Ospitante,Sede,`Ora entrata`,`Ora uscita`,Giorno from  `Archivio`");
?>

Code with filter:

 <div class="filtro">
            <form method="POST">
                <div class="textfiltro">
                    Filtra per giorno:
                </div>
                <div class="field">
                    <input type="text" name="data" id="data">
                </div>   
                <div>
                    <button class="filtrobutton">FILTRA</button>
                </div>        
            </form>
        </div>
<?php
$utente = $_POST["Utente"];
$password = $_POST["Password"];
$password = md5($password);

$id=
$sql=mysqli_query($mysqli, "select * from Utenti_Archivio where Utente='".$utente."' and          Password='".$password."'");
    if (mysqli_num_rows($sql) == 1){
    }
    else{
        header( "Location: Login.html" );
        die;
    }

$data = $_POST["data"];
if (!empty($data)) {
    $querySQL = mysqli_query($mysqli, "SELECT Nome,Cognome,Ospitante,Sede,`Ora entrata`,`Ora uscita`,Giorno FROM `Archivio` WHERE Giorno = '$data'");
} else {
    $querySQL = mysqli_query($mysqli, "SELECT Nome,Cognome,Ospitante,Sede,`Ora entrata`,`Ora uscita`,Giorno FROM `Archivio`");
}
?>

Login html file

   <body>
      <div class="login-form">
         <form id="host" action="Archivio.php" method="post">
            <div class="field">
               <input type="text" name="Utente" placeholder="Utente" required>
            </div>
            <div class="field">
               <input type="password" name="Password" placeholder="Password" required>   
            </div>
            <button type="submit">ENTRA</button>
         </form>
         <button onclick="document.location='Home.html'">INDIETRO</button>
         <button onclick="location.reload()">RIPRISTINA</button>
      </div>
    </body>

Can you help me?

I have tried moving the credential verification query after the filter and using the get method for the filter but it does not solve the problem.

Convert encoding from ISO 8859-1 to UTF-8 in PHP project

I have an old PHP project written in PHP 5.2, and am updating it to PHP 8.2

It extracts data from a SQL Server database, and on specific button presses it fills out this data into existing Excel templates.

Since PHPExcel does not exist any more I have used composer to replace it with phpspreadsheet across my project. The project is using UTF-8 for encoding (Header and meta included in my PHP and HTML), and also when connecting to the database.

PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::SQLSRV_ATTR_ENCODING => PDO::SQLSRV_ENCODING_UTF8

I have also changed the default charset = UTF-8 in my php.ini file

On my webpage all the German umlauts are showing without any problem, but the Excel files are not being filled out properly. It seems there is an encoding mismatch somewhere. In my Excel file the word Prüfung"shows like this: prüfung

The collation of my SQL Server database is Latin1_General_CI_AS.

Any ideas? I am expecting the German umlaut characters to be displayed and printed correctly.

With Nesbot Carbon diffForHumans(), display 19 months instead of 1 year when less than 26 months

I display a diffForHumans with one part

echo Carbon::create('1 hour 59 minutes ago')->diffForHumans(); // 1 hour ago
echo Carbon::create('1 day 23 hours ago')->diffForHumans(); // 1 day ago
echo Carbon::create('1 month 23 days ago')->diffForHumans(); // 1 month ago
echo Carbon::create('1 year 10 months ago')->diffForHumans(); // 1 year ago

For up to 25 months, I’d prefer to see months before it switches to year: e.g. to see 23 months instead of 1 year.

More generaly, I would like to keep the lower unit (like month) when the higher unit (like year) is 1 or 2.

I would also like the display to be as compact as possible.

How do I do that?

Woocommerce not using the right templates

I’m having some template hierarchy issues trying to add woocommerce to a custom theme I made for a client. The site isn’t using the templates it should be. The shop page the plugin generates is using ‘page.php’ instead of ‘archive-product.php’ and products are using ‘single.php’ instead of ‘single-product.php’. I created a folder called woocommerce in my theme folder and copied those two WC template files over, but they’re not being used. I used a function to force using the right templates, which worked but now the products don’t appear on the shop page like they did when the wrong templates were being used. I’ve never worked with WC before, so is there something basic I’ve missed?

Things I’ve tried:

  • switching to a default theme
  • turning off all plugins
  • double checking the folder structure (the files are in /mytheme/woocommerce/)
  • double checking the products are published
  • adding a debug line to the template echo

    Products found!

    which echoes that they are being found (just not showing)

  • checked the console for CSS or JS Issues
  • confirmed that the correct page is assigned as the Shop Page

Uncaught PHP Exception Error: “Typed property PimcoreModelDocumentDocType::$name must not be accessed before initialization” at DocType.php

I’ve been using Pimcore for a month, working on my localhost machine. Yesterday, I uploaded my Pimcore project to my server. I copied all the files and added the necessary permissions to the folders, but I keep getting the following error when I log in or refresh the page.

Would anyone be able to help?

request.CRITICAL: Uncaught PHP Exception Error: “Typed property PimcoreModelDocumentDocType::$name must not be accessed before initialization” at DocType.php line 134 {“exception”:”[object] (Error(code: 0): Typed property PimcoreModelDocumentDocType::$name must not be accessed before initialization at httpdocs/vendor/pimcore/pimcore/models/Document/DocType.php:134)”} []

I have tried looking inside every single file mention in the error log (If anybody needs the error log screenshot I will send it to you).
The only temporary solution is editing the following file:

httpdocs/vendor/pimcore/pimcore/models/Document/DocType/Listing/Dao.php
on line 60

    public static function sortByPriority(DocType $a, DocType $b): int
    {
        $a->getPriority();
        if ($a->getPriority() === $b->getPriority()) {
            return strcasecmp($a->getGroup() . $a->getName(), $b->getGroup() . $b-      >getName());
        }

        return $a->getPriority() <=> $b->getPriority();
    }

Overriding the following code by commenting the code and returning 0 the error doesn’t take place.
This doesn’t make sense for two main reasons:

  1. Is in the vendor folder so it gets frequently updated;
  2. In my local machine this error is not present, and I copied every folder 1to1 on my server.

Set Python Environment and Execute Python Code in PHP Script

I am trying to convert the vcd file to wavedrom json file using the python library

https://github.com/Toroid-io/vcd2wavedrom

when I run on my terminal the below code works fine

 source /var/www/xxx/vcd2wavedrom/verilog-env/bin/activate && 
 python3 /var/www/xxx/vcd2wavedrom/vcd2wavedrom/vcd2wavedrom.py 
 -i /var/www/xxx/uuids/abcd/dump.vcd 
 -o /var/www/xxx/uuids/abcd/dump.json

When i execute the same code in my php script as

$env = 'source /var/www/xxx/vcd2wavedrom/verilog-env/bin/activate';

cmd = "python3 /var/www/xxx/vcd2wavedrom/vcd2wavedrom/vcd2wavedrom.py -i ".$uuid_dir."/dump.vcd -o ".$uuid_dir."/dump.json";

#!/bin/sh

shell_exec($env ." && ". $cmd);

I am getting sh: 1: source: not found error.

How can set the venv from php script.

I am not a python developer. Please elaborate your answer as much as possible for me to understand better.

I tried to remove the source, but I got

 sh: 1: /var/www/xxx/vcd2wavedrom/verilog-env/bin/activate: Permission denied
 Traceback (most recent call last):
 File "/var/www/xxx/vcd2wavedrom/vcd2wavedrom/vcd2wavedrom.py", line 9, in <module>
 from vcdvcd.vcdvcd import VCDVCD
 ModuleNotFoundError: No module named 'vcdvcd'

I set verilog-env folder to 777 but still the same error persists