Is it possible to run a Windows Server Task from PHP script?

Okay, this is how you run a Windows 11 task from a PHP script that is called from a client javascript procedure.

try {

    exec('C:WindowsSystem32schtasks.exe /run /tn "DownloadFiles" > NUL 2>&1', $query_output, $query_return);
    echo json_encode([
        'success' => true,
        'message' => 'Background process started successfully.'
    ]);
    } catch (Exception $e) {
       http_response_code(500); // Internal Server Error
       echo json_encode([
        'success' => false,
        'message' => 'Error starting process: ' . $e->getMessage()
    ]);
}

Now trying to run this on Windows Server is proving impossible. I have set all the Application Pools->DefaultAppPool running under Administrato. Now I can run the tasks from powershell scripts and I can run the task manually, but I have not found a way of getting it to work from PHP or get a response that I can interpret. .

So I think I have tried most things and am more interested in if someone has actually achieved it, and not so much, “have you tried this”

Laravel 11 how to configure email encoding?

I’m sending emails from Laravel 11 app via SMTP (SendGrid) and viewing them in Gmail.

My HTML email has correct encoding configured:

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

However, when I click “Show original” in Gmail and check both text and HTML versions of the email, I see other encodings:

Either “iso-8859-1”

Content-Type: text/plain; charset=iso-8859-1
Content-Transfer-Encoding: quoted-printable
...plain text email...
Content-Type: text/html; charset=iso-8859-1
Content-Transfer-Encoding: quoted-printable
...html email...

Or “us-ascii”:

Content-Type: text/plain; charset=us-ascii
Content-Transfer-Encoding: quoted-printable
...plain text email...
Content-Type: text/html; charset=us-ascii
Content-Transfer-Encoding: quoted-printable
...html email...

I want everything to be UTF-8 of course.

For the life of me can’t find in laravel or sendgrid docs how I can configure the correct encoding. All advice given by LLMs are hallucinations or code from previous laravel versions.

Incorrect encoding creates issues when I use special characters from other languages, like german umlauts.

My email is fairly simple:

$payload = [
    'url' => route('login.verify', ['token' => $token]),
];
Mail::to($user->email)->send(new EmailOTP($payload));
<?php

namespace AppMail;

use IlluminateBusQueueable;
use IlluminateMailMailable;
use IlluminateMailMailablesContent;
use IlluminateMailMailablesEnvelope;
use IlluminateQueueSerializesModels;

class EmailOTP extends Mailable
{
    use Queueable, SerializesModels;

    public function __construct(public array $data)
    {
    }

    public function envelope(): Envelope
    {
        return new Envelope(
            subject: 'Your login link',
        );
    }

    public function content(): Content
    {
        return new Content(
            markdown: 'emails.login-link',
            with: [
                'url' => $this->data['url'],
            ],
        );
    }
}

How can I configure emails beint sent to be UTF-8?

Laravel Blade @can Not Working, But in_array(Auth::user()->getAllPermissions()) Does

I am working on a Laravel 11 project using Spatie’s Laravel Permission package for role-based access control.

I have the following Blade template where I want to conditionally display a sidebar link based on whether the authenticated user has the view_permission_categories permission.

`@php
    $userPermissions = Auth::user()->getAllPermissions()->pluck('name')-    >toArray();
@endphp

@if(in_array('view_permission_categories', $userPermissions))
<li>
    <x-nav-link href="/permissioncategories" :active="request()-    >is('permissioncategories')">Permission Categories</x-nav-link>
</li>
@endif

@can('view_permission_categories')
<li>
    <x-nav-link href="/permissioncategories" :active="request()- >is('permissioncategories')">Permission Categories</x-nav-link>
</li>
@endcan

`

The Issue:
The @if(in_array(…)) condition works as expected, and the link appears.
The @can(…) condition does NOT work, meaning the

  • inside it does not show up.

    My Questions:
    Why does @can(‘view_permission_categories’) fail, while in_array(Auth::user()->getAllPermissions()->pluck(‘name’)->toArray()) works?
    How can I debug why @can is not recognizing the permission?
    Is there something specific I need to configure for Spatie’s Laravel Permission to make @can work correctly?
    Any help would be greatly appreciated!

    What I Have Tried:

    1. Checked If the User Has the Permission:
      dd(Auth::user()->can('view_permission_categories'));

    2.Ensured Roles & Permissions Are Loaded:
    $currentUser = Auth::user()->load(‘roles.permissions’);

    Still, @can does not work.

    3.Cleared Cache:
    php artisan cache:clear
    php artisan config:clear
    php artisan view:clear
    php artisan route:clear
    php artisan permission:cache-reset

    4.Checked AuthServiceProvider.php for Gate Definitions:

    `use IlluminateSupportFacadesGate;
    public function boot()
    {
        Gate::define('view_permission_categories', function ($user) {
        return $user->hasPermissionTo('view_permission_categories');
    });
    }
    `
    
  • Woocommerce Order Quantity in Multiples for variable products

    I have variable products (beers), each product can be sold in bottles, cans or kegs.

    On cart and checkout pages I need to check whether total sum of bottles/cans in cart creates a multiple of 6. (e.g. 1 bottle of Beer01, 4 bottles of Beer02, 1 bottle of Beer03 => user is allowed to finish the order). Each bottle/can variation has a shipping class “bottle”, kegs have no shipping class.

    Tried to use this solution to limit the cart items with a certain shipping class, but it works for simple products only, not for variable ones: https://stackoverflow.com/a/47219447/4214743

    Could not find any solution, so I would really appreciate any help with this ๐Ÿ™‚

    Thanks in advance

    Webdav: Listing files and folder

    I am using the PHP library sabre/dav and try to create a very basic list of folders and files based on a Nextcloud I own. The following loop is successfully looping through my files, but I canโ€™t understand how to create links to them so I can download or open it.

    Edit: the following code will list my files and create links like: https://mynextcloud.com/remote.php/dav/files/SHARED-MEDIA/sound.mp3, if I click on those, a json viewer shows in the browser, with the message error: "Strict Cookie has not been found in request".

    Any help would be very welcome!

    $settings = array(
      'baseUri' => 'https://mynextcloud.com/remote.php/dav',
      'userName' => '*********',
      'password' => ''*********'
    );
    
    $client = new SabreDAVClient($settings);
    
    $directory = 'files/SHARED-MEDIA';
    try {
      $result = $client->propFind($directory, [
        '{DAV:}displayname',
        '{DAV:}getlastmodified',
      ], 1);
      echo "<ul>"; // Start an unordered list
      foreach ($result as $file) {
        $name = $file['{DAV:}displayname'];
        $url = $settings['baseUri'] . "/" . $directory . "/" . urlencode($name); 
        echo "<li>$name <a href='$url'>Download</a>";
        if (str_contains($name, '.mp3')) {
          echo " <audio controls><source src='$url' type='audio/mpeg'></audio>"; 
        }
        echo "</li>";
      }
      echo "</ul>";
    } catch (Exception $e) {
      echo 'Error: ' . $e->getMessage();
    }
    

    “The DELETE method is not supported for route customers. Supported methods: GET, HEAD, POST.” MethodNotAllowedHttpException”,

    Laravel 11, route doesn’t accept either PUT or DELETE methods, even when they are declared in web.php. I also tried making the put method a post with the id for the client, but it just went to the add method.

    web.php

    Route::post('customers', [CustomerController::class, 'add']);
    Route::get('customers', [CustomerController::class, 'show']);
    Route::get('customer/{id}', [CustomerController::class, 'getCustomer']);
    Route::put('customer/{id}', [CustomerController::class, 'update']);
    Route::delete('customer/{id}', [CustomerController::class, 'delete']);
    

    CustomerController

        public function update(Request $request, $id) {
            $cliente = Cliente::find($id);
    
            if (!$cliente) {
                return response()->json(['message' => 'Cliente no encontrado'], 404);
            }
    
            $validatedData = $request->validate([                
                'usuario_id' => 'sometimes|exists:usuarios,id',
                'DNI' => 'sometimes|string|max:20|unique:clientes,DNI' . $id,
                'nombre' => 'sometimes|string|max:255',
                'nombreUsuario' => 'sometimes|string|max:255',
                'apellidos' => 'sometimes|string|max:255',
                'email' => 'sometimes|email|unique:usuarios,email' . $cliente->usuario_id,
                'tlf' => 'sometimes|string|max:20',
                'direccion' => 'sometimes|string|max:255',
                'municipio' => 'sometimes|string|max:255',
                'provincia' => 'sometimes|string|max:255',
                'contrasena' => 'sometimes|string|min:8',
                
            ]);
    
            $cliente->update($validatedData);
    
            if ($request->has('usuario')) {
                $usuarioData = $request->input('usuario');
                $cliente->usuario->update($usuarioData);
            }
    
            return response()->json($cliente->load('usuario'), 200);
        }
    

    User and client tables

    User

        $table->id();
        $table->string('email')->unique();
        $table->string('contrasena');
        $table->string('nombre');
        $table->string('nombreUsuario');//->default('nombreusuario');
        $table->rememberToken();
        $table->timestamps();
    

    Client

    $table->id();
    $table->foreignId('usuario_id')->constrained()->cascadeOnDelete()->cascadeOnUpdate();
    $table->string("apellidos");
    $table->string('tlf');
    $table->string('direccion');
    $table->string('municipio');
    $table->string('provincia');
    $table->string('DNI');
    $table->timestamps();
    

    Running Windows exe to access MySQL database fails with error code: 1073741515

    When using a C program to access a MySQL database the exe produces no output but does provide an error code. Modifying the code to do a simple “Hello World” is successful. Running either of these exe programs on the Windows command line does work – ie the program to access the database returns rows of data. There are no error messages in Events (application or other).

    Development environment

    • Windows 11, Apache 2.4, MySQL 8.0.33, MSYS2 (I used: pacman -S mingw-w64-ucrt-x86_64-gcc to get gcc)
    • Using MSYS2 UCRT64 application to compile the c code
    • Compiled using: gcc firstc.c -o atest.exe -I'c:Program FilesMySQLMySQl Server 8.0include' -L'c:Program FilesMySQLMySQl Server 8.0lib' -llibmysql

    C code -> compiles to atest.exe with no errors

    #include <mysql.h>
    #include <stdio.h>
    int main() {
        MYSQL *conn;
        MYSQL_RES *res;
        MYSQL_ROW row;
        char *server   = "localhost";
        char *user     = "root";
        char *password = "local";
        char *database = "care";
        conn = mysql_init(NULL);    
        
        if (!mysql_real_connect(conn, server, user, password, database, 0, NULL, 0)) {
            printf("%sn", mysql_error(conn));
            return(5);
        }
        
        if (mysql_query(conn, "SELECT * FROM departments")) { 
            printf("%sn", mysql_error(conn));
            return(6);
        }
        
        res = mysql_use_result(conn);
        
        while ( (row = mysql_fetch_row(res)) != NULL ) {
            printf("%s %s %sn", row[1], row[2], row[0]);
        }
        
        mysql_free_result(res);
        mysql_close(conn);
    
    }
    

    Dumpbin gives with /dependents option for atest.exe:

    File Type: EXECUTABLE IMAGE
    Image has the following dependencies:
    KERNEL32.dll
    api-ms-win-crt-environment-l1-1-0.dll
    api-ms-win-crt-heap-l1-1-0.dll
    api-ms-win-crt-math-l1-1-0.dll
    api-ms-win-crt-private-l1-1-0.dll
    api-ms-win-crt-runtime-l1-1-0.dll
    api-ms-win-crt-stdio-l1-1-0.dll
    api-ms-win-crt-string-l1-1-0.dll
    api-ms-win-crt-time-l1-1-0.dll
    libmysql.dll
    

    The libmysql.dll has been copied from the MySQL folder to c:windowsSystem32 and the c:apache24htdocs folder where the PHP code an exe resides. In addition it was copied to the folder where the source C code is compiled. Reason: just in case the PHP program/exe can not find/access it in the database folders.

    PHP code to run the exe:

    <?php
    $command = "c:apache24htdocsatest.exe 2>&1"; // should access MySQL and return rows
    $response = system($command, $retval);
    echo '<hr>Response: ' . $response . '<hr>Return value: ' . $retval;
    ?>
    

    Browser window shows on running PHP code (exe which accesses MySQL):

    Response: 
    Return value: -1073741515
    

    i.e. there is no output but the error code 1073741515 is displayed

    Expecting to get back rows of data from MySQL database.

    UPDATE: 10/3/25

    I checked again the error code and it should be -1073741515 (minus 1073741515). This converts to C0000135 Hex 2s complement.

    Feedback responses:

    -1073741515 as a file system error not MySQL error? If this is the case how do I identify which file is missing? Does it suggest that the issue is a file permissions error?

    Apache runs as user: SYSTEM – The PC runs as a web server with Apache (not IIS) as the front end.

    MySQL runs as a Network Service but can also run as a local user. The application runs with MySQL “root” access.

    The PHP script runs as user SYSTEM

    I am unable to get the c++ GetUserName function working – due to a lack of c++ programming experience and missing c++ dll’s on my PC. ie my environment is set up for c programming not c++.

    Response to possible duplicates: What does Error-code 0xc0000135 (or -1073741515 Exit-code) mean when starting a Windows

    .NET Framework 3.5 is installed. Activating it starts IIS and locks out Apache. Currently it is switched off. If the issue is .NET — I can still run a “Hello World” c program from PHP but cannot run a database query written in c as an exe and both programs work when run from the command line. i.e. .NET does not seem to be the issue. My anti-virus does not block the “Hello World” problem so I have discounted this as the problem. There are no .NET errors displayed when running the app.

    I also turned on/off my anti-virus. This made no difference.

    I have checked the Event logs and can find nothing related to this issue.

    When running the app there is no message: “The application failed to initialize properly (0xc0000135)”.

    For safety, is it enought to check whether user input conforms to an expected value? Or do I need to escape it anyway? [duplicate]

    Is it enought to check whether user input conforms to an expected value, before I embed it into executed code? E.g.:

    $fruits = array(
        "Orange",
        "Banana"
    );
    
    if(isset($_GET['fruit']) && in_array($_GET['fruit'], $fruits)) {
        // embed user input in HTML page:
        echo $_GET['fruit'];
        // embed user input in shell command:
        shell_exec("script.sh $_GET['fruit']");
        // query database with user input:
        mysqli_stmt_bind_param($stmt, 's', $_GET['fruit']);
    }
    

    Or do I need to escape it with htmlspecialchars, escapeshellcmd etc. anyway?

    How to show more columns in laravel backpack?

    i’m using laravel backpack and i have a table that has a lot of columns like 10 or more.
    but in laravel backpack it is not showing them all, it is showing like 7 or 8 and not all (depending on the length of the column laber or data) meaning laravel backpack is limiting what is shwon based on size, i couldn’t find how to make it show every column, any help?

    i tried keeping the CRUD::setFromDb(); in the protected function setupListOperation() of my table controller and also tried adding the columns manually using CRUD::addColumn and it is still limiting what is shown.

    Incorrect Change Calculation (Same as Total Bill) [closed]

    I’m working on a payment feature in Laravel, but I’m facing an issue with the change (kembalian) calculation.

    When a user pays exactly the same amount as the total bill (total_tagihan, the change is incorrectly set to the total bill amount instead of 0.

    public function bayar(Request $request)
    {
        Log::info('Fungsi bayar() dipanggil', ['request' => $request->all()]);
    
        $request->validate([
            'nomor_pelanggan' => 'required|exists:pelanggans,nomor_pelanggan',
            'total_bayar' => 'required|numeric|min:0',
            'jumlah_dibayar' => 'required|numeric|min:0',
        ]);
    
        Log::info('Validasi berhasil', ['data' => $request->all()]);
    
        $pelanggan = Pelanggan::where('nomor_pelanggan', $request->nomor_pelanggan)->first();
        if (!$pelanggan) {
            Log::error('Pelanggan tidak ditemukan!', ['nomor_pelanggan' => $request->nomor_pelanggan]);
            return back()->with('error', 'Pelanggan tidak ditemukan.');
        }
    
        Log::info('Pelanggan ditemukan', ['pelanggan' => $pelanggan]);
    
        // Ambil data pemakaian pelanggan
        $pemakaians = CatatanPemakaian::where('nomor_pelanggan', $request->nomor_pelanggan)->get();
        $total_pemakaian = $pemakaians->sum('jumlah_penggunaan') ?? 0;
    
        // Hitung denda
        $total_denda = abs(Pembayaran::hitungDenda($request->nomor_pelanggan));
        Log::info('Denda dihitung', ['total_denda' => $total_denda]);
    
        // Pastikan biaya admin dan abodemen memiliki nilai
        $biaya_admin = $request->biaya_admin ?? 2500;
        
        // Cari data pembayaran terakhir untuk mendapatkan biaya abodemen
        $pembayaranTerakhir = Pembayaran::where('nomor_pelanggan', $request->nomor_pelanggan)
                                       ->orderBy('id', 'desc')
                                       ->first();
        
        $biaya_abodemen = $pembayaranTerakhir->biaya_abodemen ?? 0;
    
        // Hitung total yang harus dibayar
        $total_pembayaran = $request->total_tagihan + $total_denda + $biaya_admin + $biaya_abodemen;
    
        Log::info('Total pembayaran dari form', ['total_pembayaran' => $total_pembayaran]);
    
        $jumlah_dibayar = $request->jumlah_dibayar;
        $kembalian = $jumlah_dibayar - $total_pembayaran;
        Log::info('Total sebelum simpan', [
            'total_tagihan' => $request->total_tagihan,
            'total_denda' => $total_denda,
            'biaya_admin' => $biaya_admin,
            'biaya_abodemen' => $biaya_abodemen,
            'total_pembayaran' => $total_pembayaran,
        ]);
        
        
        if ($jumlah_dibayar < $total_pembayaran) {
            Log::error('Pembayaran gagal: Uang kurang', [
                'jumlah_dibayar' => $jumlah_dibayar,
                'total_pembayaran' => $total_pembayaran
            ]);
            return back()->with('error', 'Uang yang dibayarkan kurang dari jumlah tagihan.');
        }
    
        try {
            // Simpan pembayaran
            $pembayaran = Pembayaran::create([
                'nomor_pelanggan' => $request->nomor_pelanggan,
                'total_pemakaian' => $total_pemakaian, // โ† FIXED: Total pemakaian sekarang sudah ada
                'total_tagihan' => $request->total_bayar - $total_denda - $biaya_admin - $biaya_abodemen,
                'biaya_admin' => $biaya_admin,
                'biaya_abodemen' => $biaya_abodemen,
                'jumlah_dibayar' => $jumlah_dibayar,
                'tanggal_pembayaran' => now(),
                'denda' => $total_denda,
                'kembalian' => $kembalian,
            ]);
    
            Log::info('Pembayaran berhasil disimpan', ['pembayaran' => $pembayaran]);
            Log::info('Total tagihan:', ['total_tagihan' => $request->total_tagihan]);
            Log::info('Total denda:', ['total_denda' => $total_denda]);
            Log::info('Biaya admin:', ['biaya_admin' => $biaya_admin]);
            Log::info('Biaya abodemen:', ['biaya_abodemen' => $biaya_abodemen]);
            Log::info('Total pembayaran yang dihitung:', ['total_pembayaran' => $total_pembayaran]);
    
            
            // Update status pemakaian yang sudah dibayar
            foreach ($pemakaians as $pemakaian) {
                $pemakaian->id = $pembayaran->id;
                $pemakaian->save();
            }
            
            // Update tanggal pembayaran terakhir pelanggan
            $pelanggan->tanggal_pembayaran_terakhir = now();
            $pelanggan->save();
            Log::info('Tanggal pembayaran pelanggan diperbarui');
    
            return redirect()->route('invoice.list')->with('success', 'Pembayaran berhasil! Kembalian: Rp ' . number_format($kembalian, 0, ',', '.'));
        } catch (Exception $e) {
            Log::error('Terjadi error saat menyimpan pembayaran', ['error' => $e->getMessage(), 'trace' => $e->getTraceAsString()]);
            return back()->with('error', 'Terjadi kesalahan saat memproses pembayaran: ' . $e->getMessage());
        }
    }
    
    
    

    enter image description here

    The change successfully fixed the issue, and the refund amount is now correct

    How to deal with returned JSON data [duplicate]

    I am creating an editable row in HTML, PHP and java script.

    This is the html and php element in index.php :

    <tbody id="inforTypeTable">
                            <?php foreach ($inforTypes as $room) : ?>
                                <tr data-id="<?= $room['id'] ?>">
                                    <td><?= $room['id'] ?></td>
                                    <td contenteditable="true" class="room-type"><?= htmlspecialchars($room['room_type']) ?></td>
                                    <td contenteditable="true" class="room-desc"><?= htmlspecialchars($room['room_desc']) ?></td>
                                    <td>
                                        <i class="bi bi-floppy2-fill save-btn" title="Save" style="cursor:pointer; opacity:0.5;"></i>
                                        <i class="bi bi-trash3-fill delete-btn" title="Delete" style="cursor:pointer;"></i>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
    

    and the following is the script to handle the save-btn (I included the update and delete too):

    $(document).ready(function() {
                $('[data-bs-toggle="tooltip"]').tooltip();
    
                $('td[contenteditable="true"]').on('input', function() {
                    $(this).closest('tr').find('.save-btn').css('opacity', '1').css('cursor', 'pointer');
                });
    
                // Save changes
                $(document).on("click", ".save-btn", function() {
                    let row = $(this).closest("tr");
                    let id = row.data("id");
                    let roomType = row.find(".room-type").text().trim();
                    let roomDesc = row.find(".room-desc").text().trim();
    
                    console.log("Saving:", roomType, roomDesc);
    
                    $.post("rooms.functions.php", {
                        action: id ? "update" : "add",
                        id,
                        roomType,
                        roomDesc
                    }, function(response) {
                        console.log("Raw Response:", response); // Log the raw response
    
                        // Only parse the response if it's valid JSON
                        try {
                            let res = JSON.parse(response);
                            alert(res.message);
                            if (res.status === "success" && !id) {
                                row.attr("data-id", res.id);
                                row.find("td:first").text(res.id);
                            }
                        } catch (e) {
                            console.error("JSON Parse Error---> ", e);
                            alert("Error processing request. Please check the console for details.");
                        }
                    });
                });
    
    
                // Delete room type
                $(document).on("click", ".delete-btn", function() {
                    let row = $(this).closest("tr");
                    let id = row.data("id");
    
                    if (confirm("Are you sure you want to delete this room type?")) {
                        $.post("rooms.functions.php", {
                            action: "delete",
                            id
                        }, function(response) {
                            console.log("Raw Response (Delete):", response);
                            try {
                                let res = JSON.parse(response);
                                alert(res.message);
                                if (res.status === "success") {
                                    row.remove();
                                }
                            } catch (e) {
                                console.error("JSON Parse Error:", e);
                                alert("Error processing request. Check console for details.");
                            }
                        });
                    }
                });
    
                // Add new row
                $("#addNew").click(function() {
                    let newRow = $(`
            <tr>
                <td>New</td>
                <td contenteditable="true" class="room-type"></td>
                <td contenteditable="true" class="room-desc"></td>
                <td>
                    <i class="bi bi-floppy2-fill save-btn" title="Save" style="cursor:pointer; opacity:0.5;"></i>
                    <i class="bi bi-trash3-fill delete-btn" title="Delete" style="cursor:pointer;"></i>
                </td>
            </tr>
            `);
                    $("#roomTypeTable").append(newRow);
                });
            });
    

    The following is the php which manages the crud:

    <?php
    require '../config.php'; // Database connection
    
    header('Content-Type: application/json'); // Force JSON response
    ob_clean(); // Remove any unwanted whitespace or characters before output
    ob_start(); // Start output buffering
    
    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        $action = $_POST['action'] ?? '';
    
        if ($action === 'update') {
            $id = $_POST['id'] ?? null;
            $roomType = trim($_POST['roomType'] ?? '');
            $roomDesc = trim($_POST['roomDesc'] ?? '');
    
            if (!empty($id) && !empty($roomType) && !empty($roomDesc)) {
                $stmt = $pdo->prepare("UPDATE room_type SET room_type = ?, room_desc = ?, created_date = NOW(), created_by = 'WIAL' WHERE id = ?");
                $stmt->execute([$roomType, $roomDesc, $id]);
                echo json_encode(["status" => "success", "message" => "Room type updated successfully!"]);
            } else {
                echo json_encode(["status" => "error", "message" => "Invalid data for update."]);
            }
        } elseif ($action === 'delete') {
            $id = $_POST['id'] ?? null;
    
            if (!empty($id)) {
                $stmt = $pdo->prepare("DELETE FROM room_type WHERE id = ?");
                $stmt->execute([$id]);
                echo json_encode(["status" => "success", "message" => "Room type deleted successfully!"]);
            } else {
                echo json_encode(["status" => "error", "message" => "Invalid ID for delete."]);
            }
        } elseif ($action === 'add') {
            $roomType = trim($_POST['roomType'] ?? '');
            $roomDesc = trim($_POST['roomDesc'] ?? '');
    
            if (!empty($roomType) && !empty($roomDesc)) {
                $stmt = $pdo->prepare("INSERT INTO room_type (room_type, room_desc, created_date, created_by) VALUES (?, ?, NOW(), 'WIAL')");
                $stmt->execute([$roomType, $roomDesc]);
                $lastId = $pdo->lastInsertId(); // Get last inserted ID
                echo json_encode(["status" => "success", "message" => "Room type added successfully!", "id" => $lastId]);
            } else {
                echo json_encode(["status" => "error", "message" => "Invalid data for add."]);
            }
        } else {
            echo json_encode(["status" => "error", "message" => "Invalid action."]);
        }
        ob_end_flush(); // Send output buffer
        exit; // Ensure PHP stops execution after sending JSON
    }
    

    Add, update and delete is managed successfully, means the table in database is updated.
    however the page is not updated/refreshed. and there is error

    Raw Response (Delete): 
    Object { status: "success", message: "Room type deleted successfully!" }
    rooms.php:322:33
    JSON Parse Error: SyntaxError: JSON.parse: unexpected character at line 1 column 2 of the JSON data
        <anonymous> https://localhost/dev/index.php:324
        jQuery 7
        <anonymous> https://localhost/dev/index.php:318
        jQuery 8
        <anonymous> https://localhost/dev/index.php:280
        jQuery 13
    index.php:330:37
        <anonymous> https://localhost/dev/index.php:330
        jQuery 7
        <anonymous> https://localhost/dev/index.php:318
        jQuery 8
        <anonymous> https://localhost/dev/index.php:280
        jQuery 13
    

    Can you advise how to have the table in index.php refreshed once the operation is successfully executed?

    Is there any solution of missing code in wordpress? [closed]

    i am newbie in wordpress,the problem is each time i want to edit my page,the code in some sections gets deleted.i can’t understand what is the issue.
    can anybody help?

    I am a newbie,i tried to fix the issue via chatgpt and youtube but failed.i think it is a coding error,so i came here to get help.

    how to set private parent properties when restoring from `var_export()` in `__set_state()`?

    I’m trying to save the state of the private property in a parent class when exporting and importing without allowing access to the property anywhere else. I’m storing the state by exporting to a file.

    Take a class with private properties, export it with var_export() and initialize it with __set_state() too easy.

    Now subclass it and try the same thing. You can’t set the private property of the parent class in __set_state(). Can you?

    Maybe I should be using serialize instead but is there a way to get this to work?

    I tried:

    • Creation of dynamic property B::$priA3 is deprecated
      $obj->priA3 = $an_array['priB3'];

    • Cannot access private property A::$priA3
      parent::$priA3 = $an_array['priA3'];

    <?php
    
    $br = "----n";
    
    class A
     {
        private   $priA3;
    
        public function __construct()
         {
            $this->priA3 = 'priA3';
         }
    
        public static function __set_state($an_array)
         {
            $obj = new A;
            $obj->priA3 = $an_array['priA3'];
            return $obj;
         }
     }
    
    $a = new A;
    
    $b = var_export($a, true);
    eval('$c = ' . $b . ';');
    print_r($c);
    echo $br;
    
    class B extends A
     {
        public function __construct()
         {
            parent::__construct();
         }
    
        public static function __set_state($an_array)
         {
            $obj = new B;
    
            // |/ Creation of dynamic property B::$priA3 is deprecated
            // $obj->priA3 = $an_array['priB3'];
    
            // |/ Cannot access private property A::$priA3
            // parent::$priA3 = $an_array['priA3'];
    
            return $obj;
         }
     }
    
    $a = new B;
    $b = var_export($a, true);
    eval('$c = ' . $b . ';');
    print_r($c);
    

    Workaround I found was to either use optional parameters in the constructor for initialization of the properties, use __set() to access the overloaded property, or a protected method to set it. I don’t think these are good options.

    The parent class would create the private property so adding an optional parameter in the constructor or allowing it to be set any other way would not work, it shouldn’t be visible to anything but the parent class.

    Otherwise maybe i should be using serialize instead for this?

    i dont know why a users profile picture is not being displayed on my website content page using php [closed]

    I’ve been trying to display users selected profile picture chosen from the login page and display it on their content page but the image is not being displayed. the image file directory and image name are being inserted into the database just fine.

     if(isset($user_id)) { 
    
              $user_id = $_SESSION['user_id'];
    
    
              $sql1 = "SELECT profilepicture , id FROM user WHERE id = '$user_id' ";
              $select= mysqli_query($conn, $sql1); // just for the owner of the account.
      
              if(isset($user_id)){
    
                if(mysqli_num_rows($select)>0){
    
                  $row = mysqli_fetch_assoc($select);
    
                  echo "<img src='images/'.$row ['profilepicture']   alt='profilepicture'>"  ;
    

    i was expecting, using this code, that the users chosen profile picture will be displayed on their content page