Viewing File: /home/quiczmwg/public_html/withdrawal_process.php

<?php
// Start the session
session_start();

// Check if the 'userid' session is not set
if (!isset($_SESSION['userid'])) {
    header("Location: ./login.php");
    exit();
}

// Include database connection and other necessary files
include_once ('_db.php');

// Set the user ID from the session variable
$userid = $_SESSION['userid'];

// Check if form data is submitted
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Retrieve user ID
    $userid = $_POST['userid'];

    // Retrieve withdrawal amount
    $withdrawalAmount = $_POST['amount'];

    // Query to retrieve user's account balance
    $stmt = $conn->prepare("SELECT account_balance FROM user_login WHERE userid = ?");
    $stmt->bind_param("s", $userid);
    $stmt->execute();
    $result = $stmt->get_result();
    $row = $result->fetch_assoc();

    // Check if withdrawal amount is greater than account balance
    if ($withdrawalAmount > $row['account_balance']) {
        // Insufficient balance, set error message in session
        $_SESSION['withdrawal_error'] = "Insufficient balance. Please enter an amount less than or equal to your account balance.";
    } else {
        // Sufficient balance, proceed with withdrawal process

        // Start a transaction
        $conn->begin_transaction();

        try {
            // Insert withdrawal details into the database
            $wid = uniqid(); // Generate a unique withdrawal ID
            $walletAddress = $_POST['wallet_address'];
            
            $stmt = $conn->prepare("INSERT INTO withdrawals (wid, userid, wallet_address, amount) VALUES (?, ?, ?, ?)");
            $stmt->bind_param("ssss", $wid, $userid, $walletAddress, $withdrawalAmount);
            $stmt->execute();

            // Deduct withdrawal amount from account balance
            $newAccountBalance = $row['account_balance'] - $withdrawalAmount;
            $stmt = $conn->prepare("UPDATE user_login SET account_balance = ? WHERE userid = ?");
            $stmt->bind_param("ss", $newAccountBalance, $userid);
            $stmt->execute();

            // Commit the transaction
            $conn->commit();

            // Set success message in session
            $_SESSION['withdrawal_success'] = "Withdrawal request submitted successfully. $withdrawalAmount USD will be sent to your wallet address: $walletAddress after confirmation.";
        } catch (Exception $e) {
            // Rollback the transaction on error
            $conn->rollback();
            // Set error message in session
            $_SESSION['withdrawal_error'] = "Error processing withdrawal. Please try again later.";
        }
    }
}

// Redirect back to withdraw.php
header("Location: withdraw.php");
exit();
?>
Back to Directory File Manager
<