Jump to content

TheMasterNico

Members
  • Posts

    15
  • Joined

  • Last visited

Posts posted by TheMasterNico

  1. Estaba programando cuando fui a probar me salio ese error en la consola.

    addEvent("onPlayerLoginBG", true) 
    addEventHandler("onPlayerLoginBG", resourceRoot, 
        function(user, pass) 
            local contra = hash("sha512", string.sub(user, 0, math.floor(string.len(user)/2)) .. pass .. user) -- Crear el hash 
            dbQuery(--Comprobar que la cuenta no exista 
                function(hand) 
                    local result, num_affected_rows, last_insert_id = dbPoll(hand, 0) 
                    CheckConsulta(result, num_affected_rows, last_insert_id) 
                    if result then 
                        if num_affected_rows == 0 then outputChatBox(" ** #fff714El nombre de usuario no existe.", client, 255, 0, 0, true) 
                        else 
                            for _, row in ipairs ( result ) do 
                                outputChatBox("Password: " .. row["Password"], client, 255, 0, 0, true) 
                                if row["Password"] == contra then 
                                    outputChatBox("#ffffffBienvenido a #ff0000Blod Gamer", client, 0, 0, 0, true) 
                                    triggerClientEvent(getRootElement(), "OnPlayerFinishLogin", getRootElement()) 
                                    -- Obtener datos de la db y guardarlos 
                                    for column, value in pairs ( row ) do 
                                        exports.LoginRegister:set_data(client, column, value) 
                                    end 
                                else outputChatBox("#fff714La contraseña es incorrecta", client, 0, 0, 0, true) end 
                            end    
                        end 
                    end 
                end, 
            MYSQL, "SELECT `Password` FROM `userdata` WHERE `Cuenta` = ?", user) -- Si existe o no la cuenta 
        end 
    ) 
    

    En la linea:

    triggerClientEvent(getRootElement(), "OnPlayerFinishLogin", getRootElement()) 
    

    Lo solucione colocando getRootElement(), pero con source, client y resourceRoot no funciona. (Antes me funcionaba con "client" pero ahora no, miren y veran: https://forum.multitheftauto.com/viewtopic.php?f=146&t=87998 )

    ¿Que palabra debo usar para no utilizar getRootElement()?

  2. Acabo de hacer este registro e ingreso con mysql. Lo libero y también pido sus criticas, para ver como esta el código, si le puedo cambiar algo para que funcione mejor y cosas así.

    meta.xml

        "Nicolas Castillo (TheMasterNico)" type="gamemode" name="Blod Gamer Role Play" description="Servidor roleplay en español [blod Gamer]" /> 
        client="1.4.1" server="1.4.1" /> 
         
        

    client_login.lua

    function ShowLogin1() 
        LoginButton = guiCreateButton(0.38, 0.57, 0.10, 0.04, "Ingresar", true) 
        guiSetProperty(LoginButton, "NormalTextColour", "FFFFFFFF") 
        RegisterButton = guiCreateButton(0.52, 0.57, 0.10, 0.04, "Registro", true) 
        guiSetProperty(RegisterButton, "NormalTextColour", "FFFFFFFF") 
        --LoginSaveName = guiCreateCheckBox(0.50, 0.50, 0.12, 0.02, "Guardar cuenta.", false, true) 
        --guiSetProperty(LoginSaveName, "NormalTextColour", "FF000000") 
        LoginName = guiCreateEdit(0.50, 0.40, 0.12, 0.03, "", true) 
        guiEditSetMaxLength (LoginName, 24) -- Max Username length is 24 
        LoginPass = guiCreateEdit(0.50, 0.44, 0.12, 0.03, "", true) 
        guiEditSetMaxLength (LoginPass, 32) -- Max Password length is 32 
        guiEditSetMasked(LoginPass, true)   
        showCursor(true) 
        guiSetInputEnabled(true) 
        addEventHandler("onClientGUIClick", LoginButton, CheckLogin) -- Evento para comprobar el ingreso 
        addEventHandler("onClientGUIClick", RegisterButton, CheckRegister) -- Evento para comprobar el registro 
    end 
      
    function ShowLogin2() 
        local screenW, screenH = guiGetScreenSize() 
        dxDrawRectangle(screenW * 0.3438, screenH * 0.2894, screenW * 0.3134, screenH * 0.4225, tocolor(0, 0, 0, 255), false) 
        dxDrawRectangle(screenW * 0.3524, screenH * 0.3009, screenW * 0.2960, screenH * 0.3993, tocolor(255, 255, 255, 204), false) 
        dxDrawText("Bienvenido a Blod Gamer...", screenW * 0.3924, screenH * 0.3148, screenW * 0.6146, screenH * 0.3542, tocolor(0, 0, 0, 255), 1.20, "clear", "center", "center", false, true, false, false, false) 
        dxDrawText("Cuenta:", screenW * 0.3802, screenH * 0.4005, screenW * 0.4774, screenH * 0.4317, tocolor(0, 0, 0, 255), 0.50, "bankgothic", "center", "center", false, false, false, false, false) 
        dxDrawText("Contraseña:", screenW * 0.3802, screenH * 0.4433, screenW * 0.4774, screenH * 0.4745, tocolor(0, 0, 0, 255), 0.50, "bankgothic", "center", "center", false, false, false, false, false) 
        dxDrawText("El nombre de la cuenta no es tu nombre dentro del juego.\nSi no tienes una cuenta, se te creara al instante", screenW * 0.3802, screenH * 0.6412, screenW * 0.6146, screenH * 0.6771, tocolor(221, 0, 0, 255), 1.00, "default", "center", "center", false, true, false, false, false) 
    end 
      
    addEventHandler("onClientResourceStart", resourceRoot, ShowLogin1) 
    addEventHandler("onClientRender", root, ShowLogin2) 
      
    function CheckLogin(button, state, absoluteX, absoluteY) 
        if ComprobarNombreYPass() == 1 then 
            triggerServerEvent("CheckLoginEvent", resourceRoot, guiGetText(LoginName), guiGetText(LoginPass), 1) -- Enviar evento al server_login.lua para comprobar el ingreso 
        end 
    end 
      
    function CheckRegister(button, state, absoluteX, absoluteY) 
        if ComprobarNombreYPass() == 1 then 
            triggerServerEvent("CheckLoginEvent", getRootElement(), guiGetText(LoginName), guiGetText(LoginPass), 2) -- Enviar evento al server_login.lua para comprobar el registro 
        end 
    end 
      
    function ComprobarNombreYPass() 
        local username = guiGetText(LoginName) 
        local password = guiGetText(LoginPass) 
        if username == "" or password == "" then -- Comprobar si los campos estan llenos 
            outputChatBox("#fff714Debes llenar todos los campos para poder ingresar.", 250, 0, 0, true) 
            return 0; 
        elseif string.len(username) < 4 or  string.len(password) < 8 then -- Comprobar si tienen el largo adecuado 
            outputChatBox("#fff714El nombre debe tener mínimo 4 letras y la contraseña 8.", 255, 0, 0, true) 
            return 0; 
        elseif string.match(username, "%W") or string.match(password, "%W") then -- Que no contengan caracteres extraños 
            outputChatBox("#fff714Se encontraron caracteres extraños. Solo alfanuméricos por favor.", 255, 0, 0, true) 
            return 0; 
        end 
        return 1; 
    end 
      
    function DestroyLoginGui() 
        guiSetVisible(LoginButton, false) 
        guiSetVisible(LoginName, false) 
        guiSetVisible(LoginPass, false) 
        guiSetVisible(RegisterButton, false) 
        showCursor(false) 
        guiSetInputEnabled(false) 
        removeEventHandler( "onClientRender", root, ShowLogin2) 
    end 
    addEvent("OcultarLogin", true ) 
    addEventHandler("OcultarLogin", localPlayer, DestroyLoginGui) 
    

    server_login.lua

    local MYSQL = dbConnect("mysql", "dbname=MtaBG;host=127.0.0.1", "root", "") 
      
    function ComprobarLogin(PlayerName, PlayerPass, loginregister) -- Comprobar si esta registrado o no 
        local MitadString = math.floor(string.len(PlayerName)/2) 
        local contra = hash("sha512", string.sub(PlayerName, 0, MitadString) .. PlayerPass .. string.sub(PlayerName, MitadString+1)) 
        --dbQuery(ComprobarCuentaEnDB, MYSQL, "INSERT INTO `userdata`(`Cuenta`, `Password`) VALUES (?, ?)", PlayerName, contra) 
        dbQuery(ComprobarCuentaEnDB, {PlayerName, contra, client, loginregister}, MYSQL, "SELECT * FROM `userdata` WHERE `Cuenta` = ?", PlayerName) -- Si existe o no la cuenta 
         
    end 
    addEvent("CheckLoginEvent", true) -- Agregar el evento que se llama desde client_login.lua 
    addEventHandler("CheckLoginEvent", resourceRoot, ComprobarLogin) -- Llamar a la función cuando se llama el evento 
      
    function ComprobarCuentaEnDB(hand, NombreFinal, contra, cliente, loginregister)  
         
        local result , num_affected_rows, last_insert_id= dbPoll(hand, 0) 
        CheckConsulta(result, num_affected_rows, last_insert_id) 
        if result then 
            if loginregister == 2 then -- Registro  
                if num_affected_rows == 0 then 
                    local insert = dbQuery(MYSQL, "INSERT INTO `userdata`(`Cuenta`, `Password`) VALUES (?, ?)", NombreFinal, contra)  
                    outputChatBox("#ffffffCuenta registrada correctamente.", cliente, 0, 0, 0, true) 
                    outputChatBox("#ffffffAhora puedes dar clic en 'ingresar'.", cliente, 0, 0, 0, true) 
                    result , num_affected_rows, last_insert_id= dbPoll(insert, -1) 
                    CheckConsulta(resultado, num_affected_rows, last_insert_id) 
                else outputChatBox("#fff714La cuenta ya esta registrada.", cliente, 0, 0, 0, true) end 
            elseif loginregister == 1 then -- Ingreso 
                if num_affected_rows == 0 then 
                    outputChatBox("#fff714La cuenta no existe", cliente, 0, 0, 0, true)         
                else 
                    for _, row in ipairs ( result ) do 
                        if row["Password"] == contra then 
                            --outputChatBox("    Contraseñas iguales - ID Player: " .. row["id"], cliente) 
                            -- Spawn Player 
                            spawnPlayer(cliente, 1743.1999511719, -1863.0999755859, 13.60000038147,0.00274658) 
                            fadeCamera(cliente, true) 
                            setCameraTarget(cliente, client) 
                            outputChatBox("#ffffffBienvenido a #ff0000Blod Gamer", cliente, 0, 0, 0, true) 
                            triggerClientEvent(cliente, "OcultarLogin", cliente) 
                            -- Obtener datos de la db y guardarlos 
                            for column, value in pairs ( row ) do 
                                exports.generalgame:set_data(cliente, column, value) 
                            end 
                        else 
                    outputChatBox("#fff714La contraseña es incorrecta", cliente, 0, 0, 0, true)  
                        end 
                    end    
                end 
            end             
        end 
    end  
      
    function CheckConsulta(result, num_affected_rows, last_insert_id) 
        if result then 
            outputChatBox( "**Columnas Afectadas: " .. tostring(num_affected_rows) .. "; Ultimo ID insertado: " .. tostring(last_insert_id) ) 
        else 
            local error_code,error_msg = num_affected_rows,last_insert_id 
            outputChatBox( "**Error. Código: " .. tostring(error_code) .. ";  Error mensaje: " .. tostring(error_msg) ) 
        end 
         
    end 
      
    function crearVehiculoParaJugador(elJugador, nombreDelComando, modeloDeVehiculo) 
        outputChatBox("Data: " .. exports.generalgame:get_data(elJugador, "Cuenta"),elJugador) 
        local x,y,z = getElementPosition(elJugador) 
        x = x + 5 
        local vehiculoCreado = createVehicle(tonumber(modeloDeVehiculo),x,y,z) 
        if (vehiculoCreado == false) then --"if" es la condición, siempre debe ir acompañado de la condición y un "then". 
            outputChatBox("Error al crear vehiculo.",elJugador) --Crea un mensaje de error simple en el chat. 
        end 
    end 
    addCommandHandler("crearvehiculo", crearVehiculoParaJugador) --Y aqui creamos el manejador de comandos. 
    

    dataplayer.lua

        playerData = {} 
          
        function set_data(player_element, data_key, data_value) -- export this function 
            if type(player_element) == "nil" or type(data_key) == "nil" or type(data_value) == "nil" then return false end 
          
            if not playerData[player_element] then 
                playerData[player_element] = {} 
            end 
          
            playerData[player_element][data_key] = data_value 
            return true 
        end 
          
        function get_data(player_element, data_key) -- export this function 
            if type(player_element) == "nil" or type(data_key) == "nil" then return false end 
          
            return playerData[player_element][data_key] 
        end 
          
        function delete_data() -- you have to delete the data when the player quits 
            playerData[source] = nil 
        end 
        addEventHandler('onPlayerQuit', root, delete_data) 
    

    Base de datos:

    -- 
    -- Database: `mtabg` 
    -- 
      
    -- -------------------------------------------------------- 
      
    -- 
    -- Table structure for table `userdata` 
    -- 
      
    CREATE TABLE IF NOT EXISTS `userdata` ( 
      `id` int(5) NOT NULL AUTO_INCREMENT COMMENT 'Id del usuario', 
      `Cuenta` varchar(24) NOT NULL COMMENT 'Nombre e la cuenta', 
      `Password` varchar(128) NOT NULL COMMENT 'Contraseña', 
      `CuentaNueva` int(1) NOT NULL DEFAULT '1' COMMENT 'Ver si ya eligio un nombre', 
      `Nombre` varchar(32) NOT NULL, 
      PRIMARY KEY (`id`), 
      UNIQUE KEY `Cuenta` (`Cuenta`) 
    ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ; 
    

  3. Thanks for reply.

    I try the code and return true when consult executed correctly. But in console appear one warning:

    WARNING: generalgame\server_login.lua:15: dbExec failed; (1062) Duplicata du champ 'Nicolas' pour la clef 'Cuenta'

    How do i check if the consult is execute correctly?

  4. I try to do a registration system, but the INSERT clause not return nothing.

    This is my code

    local MYSQL = dbConnect("mysql", "dbname=MtaBG;host=127.0.0.1", "root", "") 
      
      
    function ComprobarLogin(PlayerName, PlayerPass) -- Comprobar si esta registrado o no 
        local MitadString = math.floor(string.len(PlayerName)/2) 
        -- outputChatBox("User Name: " .. string.sub(PlayerName, 0, MitadString) .. "; Password: " .. string.sub(PlayerName, MitadString+1), client) 
    end 
    addEvent("CheckLoginEvent", true) -- Agregar el evento que se llama desde client_login.lua 
    addEventHandler("CheckLoginEvent", resourceRoot, ComprobarLogin) -- Llamar a la función cuando se llama el evento 
      
    function ComprobarRegistro(PlayerName, PlayerPass) 
        local MitadString = math.floor(string.len(PlayerName)/2) 
        local contra = hash("sha512", string.sub(PlayerName, 0, MitadString) .. PlayerPass .. string.sub(PlayerName, MitadString+1)) 
        dbQuery(ComprobarCuentaEnDB, MYSQL, "INSERT INTO `userdata`(`Cuenta`, `Password`) VALUES (?, ?)", PlayerName, contra) 
    end 
      
    function ComprobarCuentaEnDB(hand)  
        outputChatBox("Start ComprobarCuentaEnDB") 
      
        local result, num_affected_rows, last_insert_id = dbPoll (hand, 0) 
      
        if result == nil then 
            outputConsole( "dbPoll result not ready yet" ) 
        elseif result == false then 
            local error_code,error_msg = num_affected_rows,last_insert_id 
            outputConsole( "dbPoll failed. Error code: " .. tostring(error_code) .. "  Error message: " .. tostring(error_msg) ) 
        else 
            outputConsole( "dbPoll succeeded. Number of affected rows: " .. tostring(num_affected_rows) .. "  Last insert id: " .. tostring(last_insert_id) ) 
        end     
        outputChatBox("End ComprobarCuentaEnDB") 
    end  
      
    addEvent("CheckRegisterEvent", true) 
    addEventHandler("CheckRegisterEvent", resourceRoot, ComprobarRegistro) 
    

    The INSERT works, insert a row in mysql.

×
×
  • Create New...