FixFX

Troubleshooting

Common issues and solutions for QBCore framework.

This guide covers common issues encountered when working with QBCore framework and their solutions.

Installation Issues

Database Connection Problems

Error: "Access denied for user"

Symptoms:

[ERROR] Access denied for user 'qbcore_user'@'localhost' (using password: YES)

Solutions:

  1. Check Database Credentials:
-- Verify user exists
SELECT User, Host FROM mysql.user WHERE User = 'qbcore_user';
 
-- If user doesn't exist, create it
CREATE USER 'qbcore_user'@'localhost' IDENTIFIED BY 'your_password';
GRANT ALL PRIVILEGES ON qbcore_server.* TO 'qbcore_user'@'localhost';
FLUSH PRIVILEGES;
  1. Verify Connection String:
# In server.cfg, ensure connection string is correct
set mysql_connection_string "mysql://qbcore_user:your_password@localhost/qbcore_server?charset=utf8mb4"
  1. Check MySQL Service:
# Windows
net start mysql80
 
# Linux
sudo systemctl start mysql
sudo systemctl status mysql

Error: "Database 'qbcore_server' doesn't exist"

Solution:

CREATE DATABASE qbcore_server CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;

Resource Loading Issues

Error: "Resource [qb-core] couldn't be started"

Symptoms:

[ERROR] Could not load resource qb-core
[ERROR] Failed to start resource qb-core

Solutions:

  1. Check Resource Path:
resources/
├── [qb]/
│   └── qb-core/    # Should be here
├── [standalone]/
└── [voice]/
  1. Verify fxmanifest.lua:
-- Check for syntax errors in fxmanifest.lua
fx_version 'cerulean'
game 'gta5'
-- Ensure proper structure
  1. Check Dependencies:
# Ensure oxmysql loads before qb-core
ensure oxmysql
ensure qb-core

Error: "Script timeout"

Symptoms:

[ERROR] Script timeout: qb-core

Solutions:

  1. Check for Infinite Loops:
-- Bad
while true do
    -- No Wait() call - causes timeout
end
 
-- Good
while true do
    Wait(1000)  -- Always include Wait()
end
  1. Database Connection Issues:
-- Check if database is accessible
local result = MySQL.query.await('SELECT 1 as test')
if not result then
    print('Database connection failed')
end

Player Data Issues

Player Data Not Loading

Error: "Player data is nil"

Symptoms:

  • Player spawns but has no data
  • Commands don't work
  • Money/job shows as nil

Solutions:

  1. Check Player Loading Events:
-- Client-side
RegisterNetEvent('QBCore:Client:OnPlayerLoaded', function()
    PlayerData = QBCore.Functions.GetPlayerData()
    print('Player data loaded:', json.encode(PlayerData))
end)
  1. Verify Database Schema:
-- Check if players table exists and has data
SELECT COUNT(*) FROM players;
DESCRIBE players;
  1. Check for Database Corruption:
-- Look for corrupted player data
SELECT citizenid, name, LENGTH(money) as money_length 
FROM players 
WHERE money IS NULL OR money = '' OR JSON_VALID(money) = 0;

Error: "Player already exists"

Symptoms:

  • Cannot create new character
  • Gets stuck on character creation

Solutions:

  1. Check for Duplicate Licenses:
-- Find duplicate licenses
SELECT license, COUNT(*) as count 
FROM players 
GROUP BY license 
HAVING count > 1;
 
-- Remove duplicates (keep most recent)
DELETE p1 FROM players p1
INNER JOIN players p2 
WHERE p1.id < p2.id AND p1.license = p2.license;
  1. Clear Character Data:
-- Remove specific player data
DELETE FROM players WHERE license = 'license:your_license_here';

Money/Job Issues

Error: "Money is not updating"

Solutions:

  1. Check Money Format:
-- Verify money is valid JSON
SELECT citizenid, money, JSON_VALID(money) as is_valid 
FROM players 
WHERE JSON_VALID(money) = 0;
 
-- Fix invalid money data
UPDATE players 
SET money = '{"cash":500,"bank":5000,"crypto":0}' 
WHERE JSON_VALID(money) = 0;
  1. Check Money Functions:
-- Server-side: Proper money handling
local Player = QBCore.Functions.GetPlayer(source)
if Player then
    local success = Player.Functions.AddMoney('cash', 1000)
    print('Money added:', success)
end

Error: "Job permissions not working"

Solutions:

  1. Verify Job Data:
-- Check job format in database
SELECT citizenid, job, JSON_VALID(job) as is_valid 
FROM players 
WHERE JSON_VALID(job) = 0;
  1. Check Job Configuration:
-- In qb-core/shared/jobs.lua
QBShared.Jobs = {
    ['police'] = {
        label = 'Law Enforcement',
        defaultDuty = true,
        offDutyPay = false,
        grades = {
            ['0'] = {name = 'Recruit', payment = 50},
            -- Ensure grades are properly defined
        },
    },
}

Resource-Specific Issues

Inventory Issues

Error: "Items not showing in inventory"

Solutions:

  1. Check Item Registration:
-- In qb-core/shared/items.lua
QBShared.Items = {
    ['my_item'] = {
        name = 'my_item',
        label = 'My Item',
        weight = 100,
        type = 'item',
        image = 'my_item.png',
        unique = false,
        useable = true,
        shouldClose = true,
        combinable = nil,
        description = 'Item description'
    }
}
  1. Verify Item Images:
qb-inventory/html/images/
└── my_item.png  # Image must exist
  1. Check Inventory Database:
-- Verify inventory structure
SELECT citizenid, inventory 
FROM players 
WHERE JSON_VALID(inventory) = 0;

Error: "Cannot use items"

Solutions:

  1. Register Item Usage:
-- Server-side
QBCore.Functions.CreateUseableItem('my_item', function(source, item)
    local Player = QBCore.Functions.GetPlayer(source)
    if Player then
        -- Item usage logic
        TriggerClientEvent('qb-myresource:client:useItem', source, item)
    end
end)
  1. Check Item Metadata:
-- Ensure item has proper metadata
local item = Player.Functions.GetItemByName('my_item')
if item and item.info then
    -- Item has metadata
end

Vehicle Issues

Error: "Vehicles not spawning"

Solutions:

  1. Check Vehicle Hash:
-- Verify vehicle model exists
local model = GetHashKey('adder')
if not IsModelInCdimage(model) then
    print('Vehicle model not found')
    return
end
  1. Check Vehicle Database:
-- Verify vehicle data
SELECT plate, vehicle, hash 
FROM player_vehicles 
WHERE hash = 0 OR vehicle = '';
  1. Vehicle Keys Issues:
-- Ensure proper key assignment
TriggerEvent('qb-vehiclekeys:server:GiveVehicleKeys', source, plate)

Phone/UI Issues

Error: "Phone not opening"

Solutions:

  1. Check Resource Dependencies:
# Ensure proper loading order
ensure qb-core
ensure qb-phone
  1. Check Phone Item:
-- Verify player has phone item
local Player = QBCore.Functions.GetPlayer(source)
local phone = Player.Functions.GetItemByName('phone')
if not phone then
    Player.Functions.AddItem('phone', 1)
end
  1. UI/NUI Issues:
-- Check for JavaScript errors in F8 console
-- Verify NUI focus
SetNuiFocus(true, true)

Performance Issues

High Resource Usage

Server Performance Problems

Symptoms:

  • High CPU usage
  • Lag/stuttering
  • Thread hitches

Solutions:

  1. Identify Resource Usage:
# In server console
resmon

# Look for resources using high CPU/memory
  1. Optimize Database Queries:
-- Bad: Multiple queries in loop
for i = 1, #players do
    MySQL.query.await('SELECT * FROM players WHERE citizenid = ?', {players[i]})
end
 
-- Good: Single query with IN clause
local citizenIds = {}
for i = 1, #players do
    citizenIds[#citizenIds + 1] = players[i]
end
local placeholders = string.rep('?,', #citizenIds):sub(1, -2)
MySQL.query.await('SELECT * FROM players WHERE citizenid IN (' .. placeholders .. ')', citizenIds)
  1. Reduce Timer Frequency:
-- Bad: Too frequent
CreateThread(function()
    while true do
        Wait(0)  -- Runs every frame
        -- Heavy operation
    end
end)
 
-- Good: Reasonable frequency
CreateThread(function()
    while true do
        Wait(5000)  -- Runs every 5 seconds
        -- Heavy operation
    end
end)

Memory Leaks

Increasing Memory Usage

Solutions:

  1. Check for Event Listeners:
-- Ensure proper cleanup
AddEventHandler('onResourceStop', function(resourceName)
    if GetCurrentResourceName() == resourceName then
        -- Cleanup code here
        for i = 1, #createdObjects do
            DeleteEntity(createdObjects[i])
        end
    end
end)
  1. Clear References:
-- Prevent memory leaks
local myData = {}
 
AddEventHandler('onResourceStop', function(resourceName)
    if GetCurrentResourceName() == resourceName then
        myData = nil
    end
end)

Debug Techniques

Logging and Debugging

Enable Debug Mode

-- In config.lua
Config.Debug = true
 
-- Debug function
local function DebugPrint(...)
    if Config.Debug then
        print('^3[DEBUG]^7', ...)
    end
end
 
-- Usage
DebugPrint('Player data:', json.encode(PlayerData))

Database Debugging

-- Check database operations
local function SafeQuery(query, parameters)
    local success, result = pcall(MySQL.query.await, query, parameters)
    if not success then
        print('^1[ERROR]^7 Database query failed:', result)
        return nil
    end
    return result
end

Console Commands for Debugging

-- Server-side debug commands
RegisterCommand('qb-debug-player', function(source, args)
    local playerId = tonumber(args[1]) or source
    local Player = QBCore.Functions.GetPlayer(playerId)
    
    if Player then
        print('=== PLAYER DEBUG ===')
        print('CitizenID:', Player.PlayerData.citizenid)
        print('Name:', Player.PlayerData.name)
        print('Job:', json.encode(Player.PlayerData.job))
        print('Money:', json.encode(Player.PlayerData.money))
        print('Position:', json.encode(Player.PlayerData.position))
    else
        print('Player not found')
    end
end, true)
 
RegisterCommand('qb-debug-db', function(source, args)
    local playerId = tonumber(args[1]) or source
    local Player = QBCore.Functions.GetPlayer(playerId)
    
    if Player then
        local result = MySQL.query.await('SELECT * FROM players WHERE citizenid = ?', {Player.PlayerData.citizenid})
        if result[1] then
            print('=== DATABASE DEBUG ===')
            print('Raw data:', json.encode(result[1]))
        end
    end
end, true)

Common Error Messages

Script Errors

ErrorCauseSolution
attempt to index a nil valueVariable not initializedCheck if variable exists before using
attempt to call a nil valueFunction doesn't existVerify function name and exports
bad argument #1 to 'pairs'Trying to iterate nil valueCheck if table exists before iteration
string expected, got nilPassing nil to string functionValidate input parameters

Database Errors

ErrorCauseSolution
Table doesn't existMissing database tableImport SQL files
Column doesn't existDatabase schema mismatchUpdate database schema
Duplicate entryTrying to insert duplicate keyUse UPDATE or INSERT IGNORE
Data too longValue exceeds column lengthIncrease column size

Prevention Best Practices

Code Quality

  1. Always Check for Nil:
local Player = QBCore.Functions.GetPlayer(source)
if not Player then return end
  1. Use Error Handling:
local success, result = pcall(function()
    return MySQL.query.await(query, params)
end)
 
if not success then
    print('Query failed:', result)
    return
end
  1. Validate Inputs:
RegisterNetEvent('myresource:server:action', function(data)
    if not data or type(data) ~= 'table' then
        return
    end
    
    if not data.amount or type(data.amount) ~= 'number' then
        return
    end
    
    -- Process valid data
end)

Testing

  1. Test with Multiple Players
  2. Test Resource Restart
  3. Test Database Disconnection
  4. Test Invalid Inputs
  5. Monitor Resource Usage

Monitoring

  1. Regular Database Backups
  2. Monitor Server Performance
  3. Check Error Logs
  4. Update Dependencies

Regular maintenance and monitoring can prevent most issues before they become problems.

Always test changes on a development server before applying to production.