-
Posts
252 -
Joined
-
Last visited
Moorcam's Achievements
-
Examples of php scripting projects without laravel?
Moorcam replied to oslon's topic in PHP Coding Help
Here's one simple script that fetches news from a news website. #!/bin/bash # Define the URL of the local news channel NEWS_URL="https://www.localnewschannel.com" # Fetch the HTML content of the news page HTML_CONTENT=$(curl -s "$NEWS_URL") # Extract the headlines using grep and sed HEADLINES=$(echo "$HTML_CONTENT" | grep -oP '(?<=<h2 class="headline">).*?(?=</h2>)') # Display the headlines echo "Latest News Headlines:" echo "$HEADLINES" There's an idea. -
Help Needed with Fetching and Updating Vehicle Data Using API
Moorcam replied to GaneshNaiknavre's topic in PHP Coding Help
The script checks if the mileage and location data are valid before attempting to update the database. If either of these checks fails, the update will be skipped. // Update the database if data is valid if ($api_miles > 0 && $latitude !== null && $longitude !== null) { $update_query = "UPDATE created_jobs SET run_km = IFNULL(run_km, 0) + ?, current_km = IFNULL(current_km, 0) + ?, latitude = ?, longitude = ? WHERE vehicle_no = ?"; $stmt = $mysqli->prepare($update_query); if ($stmt) { $stmt->bind_param("ddsss", $api_miles, $api_miles, $latitude, $longitude, $vehicle_no); if (!$stmt->execute()) { error_log("Failed to execute statement for vehicle_no {$vehicle_no}: " . $stmt->error); } else { error_log("Updated vehicle_no: {$vehicle_no} | KM Added: {$api_miles} | Lat: {$latitude} | Lng: {$longitude}"); } } else { error_log("Failed to prepare statement for vehicle_no {$vehicle_no}: " . $mysqli->error); } } else { error_log("Skipping update for vehicle_no {$vehicle_no} due to invalid data."); } See if that helps. -
This is so funny. The fact that you can't even follow forum rules and requirements when posting indicates the lazy sod that you are. If you want to learn, there is a great community of developers here who will teach you. But, at least show some effort. You don't even put your code into formatted "Code" when posting, making it almost impossible to read.
-
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.
-
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?
-
They usually go in the top of the php file where you want to use them. For example, if you want them in index.php, you open index.php and paste them at the top: <?php // index.php require_once 'path/to/PhpPresentation/src/PhpPresentation/Autoloader.php'; \PhpOffice\PhpPresentation\Autoloader::register(); require_once 'path/to/PhpOffice/Common/src/Common/Autoloader.php'; \PhpOffice\Common\Autoloader::register(); // and whatever after that ?> Just change the paths to reflect the file locations.
-
If contacting support or getting support from a hosting company appears to be an issue, I would definitely be looking elsewhere. If you are paying for hosting, I would be expecting 24 hour tech support to be included.
-
Not sure of a "Setting" in PHP as such but try this: if (password_verify($password, $hashedPassword)) { $_SESSION['user_id'] = $user['id']; $_SESSION['handle'] = $user['user_handle']; echo "Login successful! Welcome, " . htmlspecialchars($username) . "."; } else { echo "Invalid username or password."; } I removed Named Parameters: The password_verify function does not support named parameters in PHP. Therefore, I removed the 'password:' syntax to ensure the code runs correctly.
-
I personally find it pointless moving the files to outside the www or root directory. I just use the following to protect any file from direct browser access: In this example, I will display config.php with database credentials: <?php // config.php if (!defined('ACCESS_GRANTED')) { die('Access denied.'); } $databaseHost = 'localhost'; $databaseUser = 'root'; $databasePassword = 'password'; $databaseName = 'my_database'; function connectToDatabase() { global $databaseHost, $databaseUser, $databasePassword, $databaseName; $connection = new mysqli($databaseHost, $databaseUser, $databasePassword, $databaseName); if ($connection->connect_error) { die('Connection failed: ' . $connection->connect_error); } return $connection; } ?> return $connection; } And, in the file that I want to grant access to: <?php // index.php define('ACCESS_GRANTED', true); include 'config.php'; $connection = connectToDatabase(); echo 'Connected successfully to the database.'; ?> Moving files outside the www for example, is a royal pain in the buttox and requires some file permissions etc. Just my opinion.
-
I know a solution has been established, but just wanted to put my 2c in. Here is what I use to show content based on user roles: <?php $user_id = $_SESSION['user_id']; $stmt = $conn->prepare("SELECT role FROM users WHERE user_id = ?"); $stmt->bind_param("i", $user_id); $stmt->execute(); $stmt->bind_result($role); $stmt->fetch(); $stmt->close(); switch ($role) { case 'Admin': echo 'I am admin'; break; case 'Member': echo 'I am Member'; break; default: echo 'Whatever!'; ?>
-
You need to give is some information as to what the actual issue is. Otherwise nobody can or will help you. Another good tip is to encase your code into the <> tag so it shows like this: <?php // database.php require_once __DIR__ . '/config.php'; // Ensure this path correctly points to config.php /** * Establish a new database connection. * * @return mysqli The MySQLi database connection object. * @throws Exception if the connection fails. */ function db_connect() { // Use MySQLi to connect to the database $connection = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME); // Check if the connection was successful if ($connection->connect_error) { error_log("Database connection failed: " . $connection->connect_error); die("Database connection failed. Please check the error log for details."); } // Set the character set to UTF-8 for proper handling of characters if (!$connection->set_charset("utf8mb4")) { error_log("Error setting character set utf8mb4: " . $connection->error); } return $connection; } /** * Close an existing database connection. * * @param mysqli|null $connection The connection object to close. * @return void */ function db_disconnect($connection) { if ($connection instanceof mysqli) { $connection->close(); } } // Establish a connection and store it in the variable $db for use later $db = db_connect(); // You can now use $db for your database queries It makes it easier to read. Also, no need for this: if ($connection instanceof mysqli) { $connection->close(); } PHP automatically closes connections. Okay, your turn
-
Fixed. The issue was with the Javascript: // Unban User function unbanUser(userId) { Swal.fire({ title: 'Are you sure?', text: "You are about to unban this user.", icon: 'warning', showCancelButton: true, confirmButtonText: 'Yes, unban it!', cancelButtonText: 'No, cancel!', }).then((result) => { if (result.isConfirmed) { fetch("includes/unban-user.php", { method: "POST", headers: { "Content-Type": "application/x-www-form-urlencoded" }, body: `userId=${encodeURIComponent(userId)}` }) .then(response => handleResponse(response)) .catch(error => { console.error("Error:", error); Swal.fire({ title: 'Error!', text: 'There was an issue unbanning the user.', icon: 'error', confirmButtonText: 'Okay' }); }); } }); } function handleResponse(response) { if (response.ok) { response.text().then(text => { Swal.fire({ title: 'Success!', text: text, icon: 'success', confirmButtonText: 'Okay' }).then(() => { location.reload(); // Reload the page to see the changes }); }); } else { console.error("Error: " + response.statusText); Swal.fire({ title: 'Error!', text: 'There was an issue unbanning the user.', icon: 'error', confirmButtonText: 'Okay' }); } } I was missing this part: function handleResponse(response) { if (response.ok) { response.text().then(text => { Swal.fire({ title: 'Success!', text: text, icon: 'success', confirmButtonText: 'Okay' }).then(() => { location.reload(); // Reload the page to see the changes }); }); } else { console.error("Error: " + response.statusText); Swal.fire({ title: 'Error!', text: 'There was an issue unbanning the user.', icon: 'error', confirmButtonText: 'Okay' }); } } Thanks for your help regardless. Always appreciated.
-
For sweetalert to work, it replaces the alert part with Swal.fire So like so: <script>alert("Normal JS Alert");</script> <script>Swal.fire("Are you sure?","You are about to unban this user","warning");</script> See attached image Reference: https://sweetalert.js.org/
-
Here is mac_gyver's code converted to mysqli with prepared statements: <?php // Initialize the MySQLi connection $mysqli = new mysqli("localhost", "username", "password", "database"); // Check for connection errors if ($mysqli->connect_error) { die("Connection failed: " . $mysqli->connect_error); } $where_terms = []; $params = []; $types = ''; // Conditionally add the lorry term if ($lorry != 'all') { $where_terms[] = 'lorry = ?'; $params[] = $lorry; $types .= 's'; // Assuming lorry is a string } // Add the date_created term $where_terms[] = 'date_created BETWEEN ? AND ?'; $params[] = $date_start; $params[] = $date_end; $types .= 'ss'; // Assuming date_start and date_end are strings $where = implode(' AND ', $where_terms); // Build the query $sql = "SELECT * FROM `sales` WHERE $where ORDER BY date_created DESC"; // Prepare the statement $stmt = $mysqli->prepare($sql); // Check for preparation errors if ($stmt === false) { die("MySQLi prepare error: " . $mysqli->error); } // Bind parameters $stmt->bind_param($types, ...$params); // Execute the statement if (!$stmt->execute()) { die("MySQLi execute error: " . $stmt->error); } // Fetch the data $result = $stmt->get_result(); $sales_data = $result->fetch_all(MYSQLI_ASSOC); // Check if there is data to display if (empty($sales_data)) { echo "No data to display."; } else { foreach ($sales_data as $sale) { // Output the data (customize as needed) echo "Sale ID: " . $sale['id'] . "<br>"; // Add more fields as necessary } } ?> Hope this helps.
-
I know. It's not meant to. It's meant to show a Sweetalert, hence the Swal.fire instead of alert. Problem is, it IS showing a normal JS alert on this line: echo '<script>Swal.fire("Success", "User has been unbanned.", "success");</script>'; But, the JS Alert has this in it: '<script>Swal.fire("Success", "User has been unbanned.", "success");</script>'