// Include authentication and database connection before any output
require_once DIR . '/../../includes/auth.php';
require_once DIR . '/../../includes/db_connect.php';
// Constants for pagination
define('ORDERS_PER_PAGE_DEFAULT', 10);
// Helper Functions
/**
Sanitize input to prevent XSS and other injections.
@param string $input The input string to sanitize.
@return string The sanitized string.
*/
function sanitize_input(input) {
return htmlspecialchars(trim(input), ENT_QUOTES, 'UTF-8');
}
/**
Build a query string while preserving existing parameters.
@param array $new_params Associative array of new parameters to add or update.
@return string The resulting query string.
*/
function build_query(new_params = []) {
current_params = GEnew_params as value) {
if (current_params[value;
} else {
unset(key]); // Remove if value is null
}
}
// Remove parameters that shouldn't persist
unset(query = http_build_query(query ? '?' . $query : '';
}
Assistant
T
;
f
or
e
a
c
h
(
key=>
value !== null) { // Only set if value is not null
key]=
currentparams[
currentparams[′page′]);
currentparams);return
/**
Generate a WhatsApp link from a contact number.
@param string $contact The contact number.
@return string The WhatsApp URL.
*/
function generate_whatsapp_link(contact) {
// Remove any non-digit characters except the plus sign
digits = preg_replace('/[^\d+]/', '', $contact);
// Ensure the number starts with '+'
if (strpos(digits, '+') !== 0) {
digits = '+' . $digits;
}
// Remove '+' for WhatsApp URL
digits=ltrim(digits, '+');
// Search Filter
if (!empty(search)) {
where_conditions[] = "(c.name LIKE ? OR o.id LIKE ? OR c.contact LIKE ?)";
searchterm="search . "%";
parameters[]=search_term;
parameters[]=search_term;
parameters[]=search_term;
$param_types .= "sss";
}
// Date Range Filter on order_date
if (!empty(from_date)) {
where_conditions[] = "o.order_date >= ?";
parameters[]=from_date . " 00:00:00";
$param_types .= "s";
}
// Combine all where conditions
whereclause="";if(count(where_conditions) > 0) {
whereclause="WHERE".implode("AND",where_conditions);
}
// Sorting
// To prevent SQL injection in ORDER BY, use a mapping
sortcolumnmap=[′id′=sort_column = isset(sortcolumnmap[sort_by]) ? sortcolumnmap[sort_by] : 'o.order_date';
orderclause="ORDERBYsort_column $sort_order";
<!-- Bootstrap Icons JS (optional if interactivity is needed) -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.5/font/bootstrap-icons.js"></script>
<!-- UnoCSS Runtime (ensure it's loaded) -->
<script type="module">
import 'https://unpkg.com/@unocss/runtime?module';
</script>
<!-- JavaScript for Interactivity -->
<script>
// Initialize Flatpickr for date inputs
flatpickr("#fromDate", {
dateFormat: "Y-m-d",
maxDate: "today",
allowInput: true
});
flatpickr("#toDate", {
dateFormat: "Y-m-d",
maxDate: "today",
allowInput: true
});
// Function to handle sorting
function sortTable(column) {
const urlParams = new URLSearchParams(window.location.search);
let currentSortBy = urlParams.get('sort_by') || 'order_date';
let currentSortOrder = urlParams.get('sort_order') || 'DESC';
if (currentSortBy === column) {
// Toggle sort order
currentSortOrder = currentSortOrder === 'ASC' ? 'DESC' : 'ASC';
} else {
currentSortBy = column;
currentSortOrder = 'ASC';
}
urlParams.set('sort_by', currentSortBy);
urlParams.set('sort_order', currentSortOrder);
// Reset to first page if pagination is implemented
urlParams.set('page', 1);
window.location.search = urlParams.toString();
}
// Function to confirm deletion using custom modal
function confirmDelete(orderId) {
const deleteModal = document.getElementById('deleteModal');
const deleteOrderId = document.getElementById('delete_order_id');
// Set the order ID in the modal
deleteOrderId.value = orderId;
// Show the modal
deleteModal.classList.remove('hidden');
}
// Function to close delete modal
function closeDeleteModal() {
const deleteModal = document.getElementById('deleteModal');
deleteModal.classList.add('hidden');
}
// Function to open status change modal
function openStatusModal(orderId, currentStatus) {
const statusModal = document.getElementById('statusModal');
const modalOrderId = document.getElementById('modal_order_id');
const newStatusSelect = document.getElementById('newStatus');
// Set the order ID in the modal
modalOrderId.value = orderId;
// Set the current status as the default selected option
newStatusSelect.value = currentStatus;
// Show the modal
statusModal.classList.remove('hidden');
}
// Function to close status change modal
function closeStatusModal() {
const statusModal = document.getElementById('statusModal');
statusModal.classList.add('hidden');
}
// Function to mark an order as paid
function markPaid(orderId) {
if (confirm("Are you sure you want to mark this order as paid?")) {
// Create a form to submit the mark_paid action via POST
const form = document.createElement('form');
form.method = 'POST';
form.action = 'view_orders.php';
const actionInput = document.createElement('input');
actionInput.type = 'hidden';
actionInput.name = 'action';
actionInput.value = 'mark_paid';
form.appendChild(actionInput);
const orderIdInput = document.createElement('input');
orderIdInput.type = 'hidden';
orderIdInput.name = 'order_id';
orderIdInput.value = orderId;
form.appendChild(orderIdInput);
document.body.appendChild(form);
form.submit();
}
}
// Function to edit order
function editOrder(orderId) {
window.location.href = `edit_order.php?id=${orderId}`;
}
// Function to apply filters (on status change, priority change)
function applyFilters() {
const urlParams = new URLSearchParams(window.location.search);
const statusFilter = document.getElementById('statusFilter').value;
const priorityFilter = document.getElementById('priorityFilter').value;
const ordersPerPage = document.getElementById('entriesPerPage').value;
const fromDate = document.getElementById('fromDate').value;
const toDate = document.getElementById('toDate').value;
urlParams.set('status_filter', statusFilter);
urlParams.set('priority_filter', priorityFilter);
urlParams.set('orders_per_page', ordersPerPage);
urlParams.set('from_date', fromDate);
urlParams.set('to_date', toDate);
urlParams.set('page', 1); // Reset to first page
window.location.search = urlParams.toString();
}
// Function to apply date filters separately
function applyDateFilters() {
applyFilters();
}
// Close modals when clicking outside of the modal content
window.onclick = function(event) {
const deleteModal = document.getElementById('deleteModal');
const statusModal = document.getElementById('statusModal');
if (event.target == deleteModal) {
deleteModal.classList.add('hidden');
}
if (event.target == statusModal) {
statusModal.classList.add('hidden');
}
}
</script>
The error you're encountering:
code
Deprecated: htmlspecialchars(): Passing null to parameter #1 ($string) of type string is deprecated in /home/u406552082/domains/longevacare.com/public_html/kaakalia/public/orders/view_orders.php on line 800
is due to htmlspecialchars() receiving a null value for the $string parameter. In PHP 8.1 and later versions, passing null to htmlspecialchars() is deprecated and triggers warnings.
To resolve this issue and adhere to your requirement of not displaying the "Address" section when the address is not available, we'll modify the code to conditionally display the address only when it exists. Additionally, we'll ensure that htmlspecialchars() never receives a null value by providing a default empty string if necessary.
Below is the fully corrected and enhanced version of your view_orders.php file with the necessary changes applied:
function sanitize_input($input) {
return htmlspecialchars(trim($input), ENT_QUOTES, 'UTF-8');
}
Updated:
php
function sanitize_input($input) {
return htmlspecialchars(trim($input ?? ''), ENT_QUOTES, 'UTF-8');
}
Reason: Added the null coalescing operator (??) to ensure that if $input is null, it defaults to an empty string. This prevents htmlspecialchars() from receiving a null value.
<?php
// Conditionally display Address or Pickup Location
if (!$is_pickup && !empty($order['delivery_address'])):
?>
<strong>Address:</strong> <?= nl2br(htmlspecialchars($order['delivery_address'])) ?><br>
<?php endif; ?>
<?php if ($is_pickup): ?>
<!-- Optionally display the customer address if needed or just pickup location -->
<!-- Assuming pickup orders might still have an address for reference -->
<?php if (!empty($order['delivery_address'])): ?>
<strong>Address:</strong> <?= nl2br(htmlspecialchars($order['delivery_address'])) ?><br>
<?php endif; ?>
<strong>Pickup Location:</strong> <span class="text-indigo-600">Our Storefront</span>
<?php endif; ?>
Additional Recommendations
Upgrade PHP Code Practices:
Consider using the null coalescing operator (??) and other modern PHP features to enhance code robustness.
Regularly review deprecated functions and update them to align with the latest PHP standards.
Error Handling:
While debugging, displaying errors is helpful. However, in a production environment, it's recommended to disable error displays and log them instead to prevent exposing sensitive information.
Code Maintenance:
Regularly update dependencies (like Tailwind CSS, Bootstrap Icons, etc.) to benefit from security patches and new features.
Implement comprehensive validation for user inputs beyond just sanitization to ensure data integrity.
Conclusion
By implementing these changes, you ensure that the "Address" section is displayed only when appropriate, and htmlspecialchars() is never called with a null value, thereby eliminating the deprecated warnings. This approach not only resolves the immediate issue but also enhances the overall robustness and maintainability of your view_orders.php script.
The "Address" field is displayed only ifdelivery_address is not empty.
For Pickup Orders ($is_pickup):
Optionally display the customer's address if available.
Always display the "Pickup Location" regardless of the address.
Avoid Passing null to htmlspecialchars():
Implementation:
By checking !empty($order['delivery_address']) before calling htmlspecialchars(), we ensure that htmlspecialchars() never receives a null value.
Additionally, in the sanitize_input function and other areas where user-generated content is sanitized, the ?? operator ensures that a default empty string is provided.
General Improvements:
Code Readability: Enhanced comments and structure for better understanding.
Security: Continued use of prepared statements and sanitized inputs to prevent SQL injection and XSS attacks.
User Experience: Modals and interactive elements have been preserved and should function as intended.