Jump to content

Only variables should be passed by reference


Go to solution Solved by Moorcam,

Recommended Posts

Hi guys,

I have the following code, which does work. The two problematic parts are pickup_location and drop_location. When I click Save the data is saved to the database and those two are saved to an array with multiple locations.

However, opening err_log, I get the following for each one:

Only variables should be passed by reference

<?php
// Include Header file which contains required credentials
include_once('includes/header.php');

// Initialize variables
$charterData = [
    'chtr_name' => '',
    'chtr_description' => '',
    'start_date' => '',
    'end_date' => '',
    'depot_start' => '',
    'depot_finish' => '',
    'driver' => '',
    'fleet_number' => '',
    'updated_by' => '',
    'customer_name' => '',
    'pickup_location' => [],
    'drop_location' => [],
    'pickup_time' => '',
    'return_time' => ''
];

try {
    // Fetch current charter details
    $charterId = (int)$_GET['chtr_id']; // Assuming the charter ID is passed via the URL
    $fetchStmt = $conn->prepare("SELECT chtr_name, chtr_description, start_date, end_date, depot_start, depot_finish, driver, fleet_number, updated_by, customer_name, pickup_location, drop_location, pickup_time, return_time FROM charters WHERE chtr_id = ?");
    $fetchStmt->bind_param("i", $charterId);
    $fetchStmt->execute();
// Initialize variables
$pickupLocations = null; // or an appropriate default value
$dropLocations = null;   // or an appropriate default value

$fetchStmt->bind_result(
    $charterData['chtr_name'],
    $charterData['chtr_description'],
    $charterData['start_date'],
    $charterData['end_date'],
    $charterData['depot_start'],
    $charterData['depot_finish'],
    $charterData['driver'],
    $charterData['fleet_number'],
    $charterData['updated_by'],
    $charterData['customer_name'],
    $pickupLocations, // Now properly initialized
    $dropLocations,    // Now properly initialized
    $charterData['pickup_time'],
    $charterData['return_time']
);

    $fetchStmt->fetch();
    $fetchStmt->close();

    // Convert pickup and drop locations from JSON to array
    $charterData['pickup_location'] = json_decode($pickupLocations, true) ?: [];
    $charterData['drop_location'] = json_decode($dropLocations, true) ?: [];

    // Check if the form is submitted
    if ($_SERVER["REQUEST_METHOD"] === "POST") {
        // User data
        foreach ($charterData as $key => $value) {
            if ($key === 'pickup_location' || $key === 'drop_location') {
                $charterData[$key] = array_filter(array_map('htmlspecialchars', $_POST[$key] ?? []));
            } else {
                $charterData[$key] = htmlspecialchars(trim($_POST[$key] ?? ''));
            }
        }

        // Prepare an SQL statement for updating the charter
        $stmt = $conn->prepare("UPDATE charters SET chtr_name = ?, chtr_description = ?, start_date = ?, end_date = ?, depot_start = ?, depot_finish = ?, driver = ?, fleet_number = ?, updated_by = ?, customer_name = ?, pickup_location = ?, drop_location = ?, pickup_time = ?, return_time = ? WHERE chtr_id = ?");
        
        // Bind parameters
        $stmt->bind_param("ssssssssssssssi", 
            $charterData['chtr_name'], 
            $charterData['chtr_description'], 
            $charterData['start_date'], 
            $charterData['end_date'], 
            $charterData['depot_start'], 
            $charterData['depot_finish'], 
            $charterData['driver'], 
            $charterData['fleet_number'], 
            $charterData['updated_by'], 
            $charterData['customer_name'], 
            json_encode($charterData['pickup_location']), 
            json_encode($charterData['drop_location']), 
            $charterData['pickup_time'], 
            $charterData['return_time'], 
            $charterId
        );

        // Execute the statement
        if (!$stmt->execute()) {
            throw new Exception("Error: " . $stmt->error);
        }
        echo '<script type="text/javascript">
        Swal.fire({
          icon: "success",
          title: "Great Job!",
          text: "Be proud! Charter has been updated successfully!",
          showConfirmButton: false,
          timer: 2500,
          footer: "Powered by NerfCMS"
        });
        </script>';
    }
} catch (Exception $e) {
    $ErrMsg = $e->getMessage();
}
?>

Can anyone please guide me in the right direction?

  • Solution

Ok,

After more research the issue was with these two lines:

    $pickupLocations, // Now properly initialized
    $dropLocations,    // Now properly initialized

These two variables are connected to a json_encode function. And, since json_encode returns a value rather than a variable, it cannot be passed by reference.

So, the fix was to predefine the json_encode and pass them then into the bind as follows:

// Prepare JSON encoded variables
$pickupLocation = json_encode($charterData['pickup_location']);
$dropLocation = json_encode($charterData['drop_location']);

// Bind parameters
$stmt->bind_param("ssssssssssssssi", 
    $charterData['chtr_name'], 
    $charterData['chtr_description'], 
    $charterData['start_date'], 
    $charterData['end_date'], 
    $charterData['depot_start'], 
    $charterData['depot_finish'], 
    $charterData['driver'], 
    $charterData['fleet_number'], 
    $charterData['updated_by'], 
    $charterData['customer_name'], 
    $pickupLocation, 
    $dropLocation, 
    $charterData['pickup_time'], 
    $charterData['return_time'], 
    $charterId
);

Hope this may help others in the future.

Edited by Moorcam

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.