Using fpdf library creates a blank page

I get a blank page in the pdf-document, when I output a greater amount of text. I use the fpdf library. The following code (test code) is working well. When I add the commantary code I get a blank page.
The code is embedded in a wordpress CMS.

<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
$fileIncPath=getcwd();
require_once("$fileIncPath/wp-content/fpdf/fpdf.php");
$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetAutoPageBreak(false);
$pdf->SetFont('Arial','',10, true);
$pdf->Text(40,50,'Hallo Test auf Seite 1!', 0, 1);
$pdf->SetFont('Arial','',10, true);
$pdf->Text(40,60,'Hallo Test auf Seite 1!', 0, 1);
$pdf->SetFont('Arial','',10, true);
$pdf->Text(40,70,'Hallo Test auf Seite 1!', 0, 1);
$pdf->SetFont('Arial','',10, true);
$pdf->Text(40,80,'Hallo Test auf Seite 1!', 0, 1);
$pdf->SetFont('Arial','',10, true);
$pdf->Text(40,90,'Hallo Test auf Seite 1!', 0, 1);
//$pdf->SetFont('Arial','',10, true);
//$pdf->Text(40,100,'Hallo Test auf Seite 1!', 0, 1);
$pdf->SetFont('Arial','',10, true);
$pdf->Text(40,190,'Hallo Test auf Seite 1!', 0, 1);
$pdf->Output('I', 'test.pdf');
?>

I tested the code in a local environment only with php. This worked. On the server in a wordpress environment it didn’t work.

API Call by PHP [duplicate]

Good morning,

i have small problem to echo a variable. Maybe you can help me. Thanks!
https://api.openligadb.de/index.html

/getmatchdata/matchid

This works:

<?php echo $match["team1"]["teamIconUrl"]; ?>

But i’m not able to get the matchresult.

<?php echo $match["matchResults"]["pointsTeam1"]; ?>



<?php


// Retrieve the data for the current matchday from the OpenLigaDB API
$url = sprintf("https://api.openligadb.de/getmatchdata/bl1", $current);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

$output = curl_exec($ch);
 
if ($output === false) {
    die("Error when requesting the API: " . curl_error($ch));
}

curl_close($ch);

// Decoding the API response
$matches = json_decode($output, true);

if ($matches === null) {
    die("Error processing API response: " . json_last_error_msg());
}
?>

Add node.js module into PHP Apache Application for real-time communication through websockets?

I have a dedicated, managed VM on top of which I host my web app, running on PHP (FCGI) and Apache. I built a REST API in PHP, everything of the web app is an endpoint, basically. That includes the chat messaging functionality included in the app, which is thus implemented using polling to simulate real-time messaging.

I would now like to really have an actual real-time messaging solution, but ideally with as much of the codebase written in PHP being used, and a minimum amount of added work as possible.

So I first looked at solutions for websockets in PHP, but I keep reading about articles saying that PHP is not the best for websockets.

So I thought about the following architecture:

  • Install an additional node.js directory on my VM
  • In that directory, setup a websocket server responsible for the handling of ws connections
  • When a client successfully logs in, establish a new connection to the websocket server. The whole application traffic is though still going throught the REST API as until now. The ws connection is exclusively used to forward received messages to the corresponding client in real-time.
  • Create an endpoint on the node.js server, e.g. POST /forward-messages, taking an array of e.g. {message: string, id: int} objects as request arguments. When a request is received on that endpoint, the message is sent to the respective user ids provided in the request that are currently connected with the ws server.
  • When a new message is sent through the REST API (e.g. POST /messages endpoint), everything stays as it is, plus: the endpoint POST /forward-messages is triggered accordingly, internally.

I’m thinking of this solution because the messaging system setup is very tightly coupled to other components of the app, so rewriting the entire logic of it within node.js would take a significant amount of time and is at least currently not an option.

Is there any risk in this setup?

Form Data Not Inserting Into Database Despite Validation Success

I’m working on a product inventory management system using CodeIgniter. I have created a form that collects product information such as brand name, generic name, category, and pricing details. My problem is that while the form validation is successful, the data doesn’t seem to be getting inserted into the database.

Controller InventoryController.php

Here is my addProduct() function that handles the form submission, validation, and passing of data to the model:

    public function addProduct() {
            $this->load->model('Inventory_model');
            $data = $this->input->post();

            $this->load->library('form_validation');
            $this->form_validation->set_rules('brand_name', 'Brand Name', 'required');
            $this->form_validation->set_rules('generic_name', 'Generic Name', 'required');
            $this->form_validation->set_rules('category', 'Category', 'required');

            if ($this->form_validation->run() == FALSE) {
                // validation failed
                $error = array(
                    "success" => false,
                    "message" => "Validation failed"
                );
                echo json_encode($error);
            } else {
                // validation passed
                $data = array(
                    'brand_name' => $this->security->xss_clean($this->input->post('brand_name')),
                    'generic_name' => $this->security->xss_clean($this->input->post('generic_name')),
                    'category' => $this->security->xss_clean($this->input->post('category'))
                );

                $result = $this->Inventory_model->insertProduct($data);
                echo json_encode($result);
            }
        }

Model InventoryModel.php

This is my insertProduct() function in the model, which should be inserting the data into the products table:

        public function insertProduct($data) {
            $this->db->trans_start();

            $this->db->insert('products', array(
                'brand_name' => $this->security->xss_clean($data['brand_name']),
                'generic_name' => $this->security->xss_clean($data['generic_name']),
                'category' => $this->security->xss_clean($data['category'])
            ));

            
            $this->db->trans_complete();

            if ($this->db->trans_status() === FALSE) {
                $error = array(
                    "success" => false,
                    "message" => "Error adding product"
                );
                return $error;
            } else {
                try {
                    $query = "SELECT *, selling_price * quantity as total FROM products ORDER BY product_id DESC";
                    $result = $this->db->query($query, $product_id);
                    $row = $result->row_array();

                    $total = $row['total'];
                    $badge_class = $row['qty_sold'] < 10 ? 'badge-danger' : 'badge-success';

                    $response = array(
                        "success" => true,
                        "data" => array(
                            "brand_name" => $row['brand_name'],
                            "generic_name" => $row['generic_name'],
                            "category" => $row['category']
                        )
                    );
                    return $response;
                } catch (Exception $e) {
                    $error = array(
                        "success" => false,
                        "message" => "Error retrieving product data"
                    );
                    return $error;
                }
            }
        }

enable pdo-mysql with php 8.3 on centos stream

try to install pdo-mysql, but got Error: Transaction test error:
file /etc/php.d from install of php-common-8.0.30-9.el8.remi.x86_64 conflicts with file from package php83-syspaths-8.3-1.el8.remi.x86_64

anyone can explain to me how to solve this issue?

I tried “dnf –allowerasing install php-pdo* -y”

Different sources for composer package

I need to use different sources for local environment and any other (CI/Staging/Test/Production/e.t.c.).

My composer.json looks next way:

{
    "name": "laravel/laravel",
    "type": "project",
    "license": "proprietary",
    "require": {
        ...
        "my/package": "^2|@dev"
    },
    "config": {
        "preferred-install": {
            "my/package": "source",
            "*": "dist"
        }
    },
    "minimum-stability": "stable",
    "prefer-stable": false,
    "repositories": [
        {
            "type": "path",
            "url": "../path/to/package/in/local/environment",
            "options": {
                "symlink": true
            }
        },
        {
            "type": "composer",
            "url": "https://private.registry.of/my/package"
        }
    ]
}

In local environment it works, but when I execute composer install at production it throws:
Source path "../path/to/package/in/local/environment" is not found for package my/package. Which is understandable, but I can’t understand why it doesn’t try to get package from registry.

Why is there a random number popping in my code? [closed]

There is a random number popping in pages of my code and i cant seem to find where it came from i already tried inspecting it form the browser and even finding it in my codes but its not showing up anybody here experienced the same thing? how do i fix it?

Click here for the image(The red cicrcle shows the random number and the red arrow shows where is it in the inspect)

I tried searching it in my code but i could not find it and also try inspecting it in browser but i had no luck

I want to remove the random number – is there any possible way to do it?

any free web software solutions for ZKTeco K40? [closed]

I am using a ZKTeco K40 attendance device and am looking for a free web-based software to manage the attendance data. I would appreciate any recommendations for software that supports ZKTeco K40 and offers basic functionalities like attendance tracking, reporting, and user management.
Thank you!

I am using a ZKTeco K40 attendance device and am looking for a free web-based software to manage the attendance data. I would appreciate any recommendations for software that supports ZKTeco K40 and offers basic functionalities like attendance tracking, reporting, and user management.

Mysqli Extension for very old Linux OS MYSQL PHP Repo

Client is running WordPress on a very, very old Linux OS (Cent OS 6) and WordPress is complaining that mysqli extension for PHP is missing.

I tried to add it via yum but it is missing in the rpm. I absolutely do not find any location from where to get the neceassry repo files – anyone have an idea how to get mysqli extension installed anyway (and yes, they are in the process of upgrading an up to date Linux VPS, of course).

Modified /etc/yum.repos.d/remi.repo, added several repo urls, no success.

How do I append to separate excel file

public function UploadExcelData(Request $request)
    {
        Log::info('Uploading file:', ['file' => $request->file('file')]);

        //Disabled for now, this cant detect xlsx file correctly, causing it to always fail uploading

        /*  $request->validate([
              'file' => 'required|mimes:xlsx,xls',
          ]);

          */
        $filePath = 'excel/UnitTracker.xlsx';

        if (!Storage::disk('public')->exists($filePath)) {
            return response()->json(['message' => 'UnitTracker.xlsx file not found.'], 404);
        }

        $path = Storage::disk('public')->path($filePath);
        $existingData = Excel::toArray([], $path);


        $uploadedFile = $request->file('file');
        $uploadedData = Excel::toArray([], $uploadedFile);


        if (empty($uploadedData) || empty($uploadedData[0])) {
            return response()->json(['message' => 'Uploaded Excel file contains no data.'], 400);
        }

        /*
        Appended Column
        0 = Machine Type (A)
        1 = Manufacturer (B)
        2 = Model (C)
        3 = Type (D)
        4 = Serial Number (E)
        27 = Customer Name (AB)
        67 = Working Hour (BP)
        68 = Actual Working Hour (BQ)
        120 = Period From (DQ)
        121 = Period To (DR)
        5 = Customer Machine No (F)
        61 = SMR[H] (BJ)
        94 = Fuel Consumption [L/H] (CQ)
        96 = Idling Hour Ratio[%] (CS)
        72 = E Mode In Actual Working Hour (CA)
        */
        $columnsToAppend = [0, 1, 2, 3, 4, 67, 68, 120, 121, 27, 5, 61, 94, 96, 72];
        $sheets = [];

        foreach ($uploadedData as $sheetIndex => $sheet) {
            foreach ($sheet as $rowIndex => $row) {
                $currentSheetIndex = $rowIndex;
                $newRowData = [];
                foreach ($columnsToAppend as $colIndex) {
                    $value = isset($row[$colIndex]) ? $row[$colIndex] : null;

                    // Convert Working Hour (67) and Actual Working Hour (68) to dates
                    if (preg_match('/^d{2}/d{2}/d{4}$/', $value)) {
                        $newRowData[] = CarbonCarbon::createFromFormat('m/d/Y', $value)->toDateString();

                    } else {
                        $newRowData[] = $value;
                    }
                }

                if (isset($existingData[$currentSheetIndex])) {
                    $sheetData = $existingData[$currentSheetIndex];
                } else {
                    $sheetData = [];
                }

                $sheets[$currentSheetIndex] = new DataExport($sheetData, [$newRowData]);
            }
        }

        $multiSheetExport = new RowHandlerExport($sheets);


        Excel::store(new RowHandlerExport($sheets), $filePath, 'public');

        $originalName = $uploadedFile->getClientOriginalName();
        Log::info('Data appended from file: ' . $originalName);

        return response()->json(['message' => 'Data appended successfully.'], 200);
    }

So I was trying to append the excel data basically like this
File 1 row 1 is appended to sheet 1 row 1.
File 2 row 1 is appended to sheet 1 row 2.
File 1 row 2 is appended to sheet 2 row 1.
File 2 row 2 is appended to sheet 2 row 2.

it works here, but rn it’s only for a single file, I need to be able to append this to a new excel file based on the customer name (row 27) in excel

How do I append it to different excel file, I’m kinda clueless on this

Fatal error: Uncaught ValueError from XML

Could you help me? I extract data from an XML file and sometimes the code stops with a fatal error. Sometimes good, sometimes not. How should I modify the attached code snippet so that it doesn’t get 0 and run on Fatal Error?
I get this error:

Warning: Attempt to read property “any” on null in /…/VisionSoap.php on line 169
Fatal error: Uncaught ValueError: DOMDocument::loadXML(): Argument #1 ($source) must not be empty in /…/Soap.php:38
Stack trace:
#0 /…/Soap.php(38): DOMDocument->loadXML(”)
#1 /…/VisionSoap.php(169): soapSoap->save(NULL, ‘/…..’)
#2 /…/Downloader.php(55): soapVisionSoap->getMethodArValtozasAuth()
#3 /…/Downloader.php(29): downloaderDownloader->downloadWithSoap(true)
#4 /…/WholeSaleDownloader.php(44): downloaderDownloader->run(true)
#5 /…/App.php(64): downloaderWholeSaleDownloader->run(true)
#6 /…/update.php(22): appApp->update()
#7 {main}
thrown in /…Soap.php on line 38

I am attaching the mentioned part of the code as an image.

What should I change so that it doesn’t run into an error?

It gets the data from an XML that is updated on a daily basis, which probably contains some false data, which causes my code to hang.

Moodle Use Webservice for store data

I’m currently trying to write data from the app into the database. I’m using the web service for this.

However, I get the following error message and the documentation is, in my opinion, very sparse.

core_externalexternal_multiple_structure::__ construct(): Argument #1
($Content) must be of type core_externalexternal_description, array
given, called in

The relevant line is the following:

'eintraege' => new external_multiple_structure([

The complete function is:

public static function execute_returns(): external_single_structure {
        return new external_single_structure([
            'eintraege' => new external_multiple_structure([
                    'fach' => new external_value(PARAM_INT, 'FachID'),
                    'datum' => new external_value(PARAM_RAW, 'Datum des Eintrags'),
                    'ustdbis' => new external_value(PARAM_INT, 'USTD bis'),
                    'ustdvon' => new external_value(PARAM_INT, 'USTD von'),
                    'eintrag' => new external_value(PARAM_TEXT, 'Eintrag'),
            ])
        ]);
    }

I would be very grateful for any help and thank you very much for that!

I tried the following variations:
`A parameter can be described as:

a list => external_multiple_structure
an object => external_single_structure
a primary type => external_value`

As described here:
https://moodledev.io/docs/4.5/apis/subsystems/external/writing-a-service

Livewire poll stops updating during a function execution

I have a function that makes a few requests to external APIs and takes a little long to finish.

I have a status variable in my livewire component and a poll component updating it in the view, and it works fine.

During the function execution, however, I have a foreach and update the status variable with the progress every iteration, but the frontend stops sending the update ajax to the server, and the progress is not displayed.

How can I make the status update work during the function execution? Any help will be appreciated.

Page:

<x-filament-panels::page wire:poll.750ms="getStatus">
    <form wire:submit.prevent='generate'>
        {{ $this->form }}
        <x-button type="submit" class="mt-4">
            Submit
        </x-button>
    </form>


    <div >
        {{ $this->getStatus() }}
    </div>
</x-filament-panels::page>

Component:

    public $status = 'Ready to start!';

    public function updateStatus($message){
        $this->status = $message;
    }

    public function getStatus(){
        return $this->status . time();
    }

    public function generate(){

// Not relevant code

        foreach (json_decode($result->choices[0]->message->content) as $key=>$person){
            $this->updateStatus('Generating ' . $key. ' of ' . $amount . '.');
        }
// Not relevant code
    }

Im using Livewire 3 with Filament.

dynamic row discarded from an HTML form why?

I have an HTML page in which I add some form row interactively via JS, the php code that i wrote to save the content of this row and of other field on different table on db save only the first row while discard all other row added dinamically, the form action is post and the enctype is multipart/form-data

this is the part of the page that add the row:

<body>
    <div class="container">
        <h2>Create Estimate</h2>

        <?php if (isset($message)): ?>
            <div class="message"><?php echo $message; ?></div>
        <?php endif; ?>

        <div class="formintestazione">
            <form method="POST" action="create_estimate.php" onsubmit="return validateForm();" enctype="multipart/form-data">
                <div class="section">
                    <div class="form-row">
                        <label for="location">Location:</label>
                        <input type="text" id="location" name="location" value="Sciacca" required>
                    </div>

                    <div class="form-row">
                        <label for="date">Date:</label>
                        <input type="date" id="date" name="date" value="<?php echo date('Y-m-d'); ?>" required>
                    </div>

                    <div class="form-row">
                        <label for="estimate_type">Estimate Type:</label>
                        <select id="estimate_type" name="estimate_type" onchange="updateEstimateNumber()" required>
                            <option value="">Select Estimate Type</option>
                            <option value="OFF_n">OFF_n</option>
                            <option value="OFF_B2B">OFF_B2B</option>
                            <option value="OFF_EGov_n">OFF_EGov_n</option>
                        </select>
                    </div>

                    <div class="form-row">
                        <label for="estimate_number">Estimate Number:</label>
                        <input type="text" id="estimate_number" name="estimate_number" required>
                    </div>

                    <div class="form-row">
                        <label for="recipient_id">Recipient:</label>
                        <select id="recipient_id" name="recipient_id" onchange="updateRecipientDetails()" required>
                            <option value="">Select Recipient</option>
                            <?php foreach ($recipients as $recipient): ?>
                                <option value="<?php echo $recipient['id']; ?>"
                                        data-details="<?php echo $recipient['address'] . ', ' . $recipient['zip_code'] . ' - ' . $recipient['city'] . ' - ' . $recipient['province']; ?>">
                                    <?php echo $recipient['company_name']; ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>

                    <p id="recipientDetails"></p> <div class="form-row">
                        <label for="editor">Editor:</label>
                        <input type="text" id="editor" name="editor" required>
                    </div>

                    <div class="form-row">
                        <label for="subject">Subject:</label>
                        <textarea id="subject" name="subject" maxlength="255" rows="3" required></textarea>
                    </div>

                    <input type="hidden" id="draft" name="draft" value="YES">
                </div>
            </div>
            <div class="section">
                <h2>Add Estimate Items</h2>

                <div id="items-container">
                    <div class="item" data-item-number="1">
                        <h3>Item 1</h3>
                        <div class="form-row">
                            <label for="item_number_1">Item Number:</label>
                            <input type="text" id="item_number_1" name="item_number[]" value="1" readonly>
                        </div>
                        <div class="form-row">
                            <label for="item_type_1">Item Type:</label>
                            <select id="item_type_1" name="item_type[]" onchange="handlePrice(1)">
                                <option value="paragraph">Paragraph</option>
                                <option value="description">Description</option>
                            </select>
                        </div>
                        <div class="form-row">
                            <label for="image_1">Image:</label>
                            <input type="file" id="image_1" name="image[]">
                        </div>
                        <div class="form-row">
                            <label for="description_1">Description:</label>
                            <textarea id="description_1" name="description[]" rows="3"></textarea>
                        </div>
                        <div class="form-row">
                            <label for="price_1">Price (€):</label>
                            <input type="number" step="0.01" id="price_1" name="price[]">
                        </div>
                        <button type="button" class="remove-row-btn" onclick="removeItem(this)">Remove Item</button>
                    </div>
                </div>

                <button type="button" class="add-row-btn" onclick="addItem()">Add Item</button>
            </div>
            <div class="form-row">
                <button type="submit" name="save" value="Save" class="add-row-btn">Save Estimate</button>
            </div>
        </form>
    </div>
    <script>
        let itemNumber = 1;

        // Function to add a new item
        function addItem() {
            itemNumber++;
            const itemsContainer = document.getElementById('items-container');

            const newItem = document.createElement('div');
            newItem.classList.add('item');   

            newItem.setAttribute('data-item-number', itemNumber);

            newItem.innerHTML = `
                <h3>Item ${itemNumber}</h3>
                <div class="form-row">
                    <label for="item_number_${itemNumber}">Item Number:</label>
                    <input type="text" id="item_number_${itemNumber}" name="item_number[]" value="${itemNumber}" readonly>
                </div>
                <div class="form-row">
                    <label for="item_type_${itemNumber}">Item Type:</label>
                    <select id="item_type_${itemNumber}" name="item_type[]" onchange="handlePrice(${itemNumber})">
                        <option value="paragraph">Paragraph</option>
                        <option value="description">Description</option>
                    </select>
                </div>
                <div class="form-row">
                    <label for="image_${itemNumber}">Image:</label>
                    <input type="file" id="image_${itemNumber}" name="image[]">
                </div>
                <div class="form-row">
                    <label for="description_${itemNumber}">Description:</label>
                    <textarea id="description_${itemNumber}" name="description[]" rows="3"></textarea>
                </div>
                <div class="form-row">
                    <label for="price_${itemNumber}">Price (€):</label>
                    <input type="number" step="0.01" id="price_${itemNumber}" name="price[]">
                </div>
                <button type="button" class="remove-row-btn" onclick="removeItem(this)">Remove Item</button>
            `;

            itemsContainer.appendChild(newItem);
        }

        // Function to remove an item
        function removeItem(button) {
            const item = button.closest('.item');
            item.remove();
        }

        // Function to handle the price field based on the item type
        function handlePrice(itemNumber) {
            const itemType = document.getElementById(`item_type_${itemNumber}`).value;
            const priceField = document.getElementById(`price_${itemNumber}`);

            if (itemType === 'paragraph') {
                priceField.disabled = true;
                priceField.value = ''; // Reset the price field if disabled
            } else {
                priceField.disabled = false;
            }
        }

        // Initialization of the first item
        document.getElementById('item_type_1').addEventListener('change', function() {
            handlePrice(1);
        });
    </script>
</body>

 

While the php code that save the content is the following, it seems that it discard all the row added successively via js and doesn’t store the same, why the row were discarded i have developed another example in which all seems functioning correctly and even no row were discarded

<?php
// Enable error reporting for development purposes (remove in production)
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

// Database connection
$servername = "localhost";
$username   
 = "root";
$password = "";
$dbname = "tli_estimates"; // Replace with your database name

$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);   

}

// Retrieve a list of recipients from the Customers table with all details
$sql = "SELECT id, company_name, address, zip_code, city, province FROM Customers";
$result = $conn->query($sql);
$recipients = [];
if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        $recipients[] = $row;
    }
}

// Handle form submission
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Get form data
    $location = $_POST['location'];
    $date = $_POST['date'];
    $estimate_type = $_POST['estimate_type'];
    $estimate_number = $_POST['estimate_number'];
    $recipient_id = $_POST['recipient_id'];
    $editor = $_POST['editor'];
    $subject = $_POST['subject'];
    $draft = $_POST['draft'];

    // Insert the estimate into the Estimates table
    $sqlEstimate = "INSERT INTO Estimates (estimate_number, estimate_type, recipient_id, location, date, editor, subject, draft)
                  VALUES ('$estimate_number', '$estimate_type', '$recipient_id', '$location', '$data', '$editor', '$subject', '$draft')";

    if ($conn->query($sqlEstimate) === TRUE) {
        $message = ($draft == 'SI') ? "Estimate saved as draft!" : "Estimate saved successfully!";
    } else {
        $message = "Error during insertion: " . $conn->error;
    }

    // Handle estimate items
    // Get the estimate number
    $estimate_number = isset($_POST['estimate_number']) ? $_POST['estimate_number'] : null;

    // If the estimate number is empty, stop here
    if (empty($estimate_number)) {
        die("Error: Missing estimate number.");
    }

    // Loop through all submitted items
    if (isset($_POST['item_number']) && is_array($_POST['item_number'])) {
        foreach ($_POST['item_number'] as $index => $item_number) {
            // Get data from the current item
            $item_type = $_POST['item_type'][$index];
            $description = $_POST['description'][$index];
            $price = ($_POST['price'][$index] != "") ? $_POST['price'][$index] : 0.00; // If empty, set to 0.00

            // Handle image upload as a BLOB
            $image = null;
            if (isset($_FILES['image']['tmp_name'][$index]) && is_uploaded_file($_FILES['image']['tmp_name'][$index])) {
                $image = addslashes(file_get_contents($_FILES['image']['tmp_name'][$index]));
            }

            // Insert the item into the database
            $sqlItem = "INSERT INTO EstimateItems (estimate_number, item_number, item_type, image, description, price)
                       VALUES (?, ?, ?, ?, ?, ?)";

            // Prepare the SQL statement
            $stmt = $conn->prepare($sqlItem);
            if (!$stmt) {
                die("Error preparing statement: " . $conn->error);
            }

            // Bind parameters
            $stmt->bind_param("sisssd", $estimate_number, $item_number, $item_type, $image, $description, $price);

            // Execute the query
            if ($stmt->execute()) {
                echo "Item $item_number inserted successfully!<br>";
            } else {
                echo "Error inserting item $item_number: " . $stmt->error . "<br>";
            }

            // Close the statement
            $stmt->close();
        }
    } else {
        echo "Error: No items found.";
    }
}
$conn->close();