Jump to content

Search the Community

Showing results for tags 'database'.

  • Search By Tags

    Type tags separated by commas.
  • Search By Author

Content Type


Forums

  • Multi Theft Auto: San Andreas 1.x
    • Support for MTA:SA 1.x
    • User Guides
    • Open Source Contributors
    • Suggestions
    • Ban appeals
  • General MTA
    • News
    • Media
    • Site/Forum/Discord/Mantis/Wiki related
    • MTA Chat
    • Other languages
  • MTA Community
    • Scripting
    • Maps
    • Resources
    • Other Creations & GTA modding
    • Competitive gameplay
    • Servers
  • Other
    • General
    • Multi Theft Auto 0.5r2
    • Third party GTA mods
  • Archive
    • Archived Items
    • Trash

Find results in...

Find results that contain...


Date Created

  • Start

    End


Last Updated

  • Start

    End


Filter by number of...

Joined

  • Start

    End


Group


About Me


Member Title


Gang


Location


Occupation


Interests

  1. Hello everybody! I'd like to introduce you my own-made systems based on internal.db for small gamemodes or simple servers. I was thinking about how good it'd be if we'd have an abillity to work with account's saved data better and faster only using standard MTA database. I've been looking for an information that could help me to put a lot of data (as player's position, skin, money and so on) in 1 key to internal.db account's data. As for me - this is the best way of using saveAccountData() for non-global servers because it reduces the amount of trash-files in database. I made some researches on that and found out that it doesn't affect the perfomance. Download: https://community.multitheftauto.com/index.php?p=resources&s=details&id=18786 Preview: ------------------------------- ----ACCOUNT ID SYSTEM UTILS---- ------------------------------- function getAccountDatabaseID( account ) if account and not isGuestAccount( account ) then accID = 0 -- Set account ID to default if getAccountData( account, "data" ) and getAccountData( account, "data" ) ~= nil then -- Check out for account's data table local data = fromJSON( getAccountData( account, "data" ) ) -- Get account's data table if data[ "ID" ] == nil then accID = 0 -- Set account ID to default in cause of ID == nil else accID = data[ "ID" ] -- Set account ID to account's data table ID end else accID = 0 -- Set account ID to default in cause of account's data table == nil end return accID -- Return account's ID end end function getFreeDatabaseID() local accounts = getAccounts() missedID = false -- Set an ID to default for operation for i, v in pairs( accounts ) do -- Start a loop for all server accounts if i ~= getAccountDatabaseID( v ) then missedID = i break end end if missedID ~= false then return missedID --[[ ETC: There were 5 accounts. The 3rd one have been deleted. To avoid dissolution of an ID after deleting account we look for the gap and fill it with new account. It means that new account, created afther the 5th, would get 3rd ID of deleted account. --]] else return #accounts + 1 -- There were no gaps in ID row, so we return ID as a count of all accounts + created one. end end ----------------------------------------- ----ACCOUNT ID SYSTEM UTILS ENDS HERE---- ----------------------------------------- -------------------------- ----ACCOUNT DATA TABLE---- -------------------------- function getAccountDataTable( account ) if account and not isGuestAccount( account ) then if getAccountData( account, "data" ) and getAccountData( account, "data" ) ~= nil then local data = fromJSON( getAccountData( account, "data" ) ) -- Get account data table local id = data[ "ID" ] -- Get account ID from data table local position = data[ "Position" ] -- Get account position from data table local skin = data[ "Skin" ] -- Get account skin from data table local money = data[ "Money" ] -- Get account money from data table return id, position, skin, money -- Return all collected data end end end function saveAccountDataTable( account, data ) if account and not isGuestAccount( account ) then setAccountData( account, "data", data ) end end addEvent( "saveAccountDataTable", true ) addEventHandler( "saveAccountDataTable", getRootElement(), saveAccountDataTable ) function getPlayerDataTable( player ) local x, y, z = getElementPosition( player ) -- Get player's position local rotx, roty, rotz = getElementRotation( player ) -- Get player's rotation local interior = getElementInterior( player ) -- Get player's current interior local dimension = getElementDimension( player ) -- Get player's current dimension local skin = getElementModel( player ) -- Get player's skin local money = getPlayerMoney( player ) -- Get player's money local accID = getElementData( player, "ID" ) or 0 -- Get player's account ID ---- local data = toJSON( { [ "ID" ] = accID, -- Prepare account ID to save [ "Position" ] = { x, y, z, rotz, interior, dimension }, -- Prepare player's position to save [ "Skin" ] = skin, -- Prepare skin to save [ "Money" ] = money, -- Prepare money to save } ) ---- return data -- Return all data that we've collected from the player end ------------------------------------ ----ACCOUNT DATA TABLE ENDS HERE---- ------------------------------------ ---------------------------------------- ----IMPLEMENT ALL STUFF THAT WE HAVE---- ---------------------------------------- addEventHandler( "onPlayerLogin", getRootElement(), function( _, account ) if account and not isGuestAccount( account ) then if getAccountData( account, "data" ) and getAccountData( account, "data" ) ~= nil then ---------------------------------------------------- ----Spawn player from saved account's data table---- ---------------------------------------------------- local ID, position, skin, money = getAccountDataTable( account ) spawnPlayer( source, position[ 1 ], position[ 2 ], position[ 3 ], position[ 4 ], skin, position[ 5 ], position[ 6 ] ) fadeCamera( source, true, 3 ) setCameraTarget( source, source ) setPlayerMoney( source, money, true ) setElementData( source, "ID", ID ) -- Apply player's ID outputChatBox( "Welcome back, "..getPlayerName( source ).."!", source, 255, 255, 255, true ) -- Output a welcome message outputChatBox( "Your ID: "..ID, source, 255, 255, 255, true ) -- Output a message to chat for logged player to make a sure that we've got the right ID else ------------------------------------------------------------------------------- ----Spawn player for the first time or in cause of data table reading error---- ------------------------------------------------------------------------------- local ID = getFreeDatabaseID() -- Get free ID for our player to apply it later spawnPlayer( source, 0, 0, 0, 0, 0, 0, 0 ) fadeCamera( source, true, 3 ) setCameraTarget( source, source ) setPlayerMoney( source, 0, true ) setElementData( source, "ID", ID ) -- Apply player's ID outputChatBox( "First time, "..getPlayerName( source ).."? Welcome!", source, 255, 255, 255, true ) -- Output a welcome message outputChatBox( "Your ID: "..ID, source, 255, 255, 255, true ) -- Output a message to chat for logged player to make a sure that we've got the right ID end end end) addEventHandler( "onPlayerLogout", getRootElement(), function( account, _ ) local data = getPlayerDataTable( source ) -- Get player's data to save it saveAccountDataTable( account, data ) -- Save player's data table on log out end) addEventHandler( "onPlayerQuit", getRootElement(), function() local account = getPlayerAccount( source ) local data = getPlayerDataTable( source ) -- Get player's data to save it saveAccountDataTable( account, data ) -- Save player's data table on exit end) P.S: I appreciate any opinion and advice, thank you!? You can use this script for any purpose - the code is opened! I've also tried to explain the whole script. I hope it'd help! Download: https://community.multitheftauto.com/index.php?p=resources&s=details&id=18786
  2. Este es el código que he hecho hasta ahora... AreaGuerra = { 1, 1577.6806640625, 663.0947265625, 180, 120, , 0, 0, 0, 1698.1025390625, 679.1884765625, 14.822175979614 } function tables1 () executeSQLQuery("CREATE TABLE IF NOT EXISTS Gang_truf (ID INTEGER, X REAL, Y REAL, W REAL, H REAL, Gang STRING, R, G, B, sX REAL, sY REAL, sZ REAL)") for i, tables in ipairs(AreaGuerra) do local ID, X, Y, W, H, Gang, R, G, B, sX, sY, sZ = tables[1], tables[2], tables[3], tables[4], tables[5], tables[6], tables[7], tables[8], tables[9], tables[10], tables[11], tables[12] executeSQLQuery("insert into Gang_truf(ID, X, Y, W, H, Gang, R, G, B, sX, sY, sZ) values(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", ID, X, Y, W, H, Gang, R, G, B, sX, sY, sZ) end addEventHandler("onResourceStart", getResourceRootElement(getThisResource()), tables1)
  3. Database Problems Hello, I'm a beginner in this type of development, and I never used before any database, but I want to learn how to connect the database and the server, I'm just really struggling with databases, and I didn't found anything helpful for beginners, and I definitely don't know how to make my own script, so I downloaded a database system from MTA Community, and I tried to figure it out by myself, but no matter what I did, I couldn't connect the database and the server together, here is a picture of my problem: The steps I did to make a connection to the database I tried to do the exact same steps as the Script Author wrote it down in points but I failed in the first step, which is to configure my database configurations in server.lua I Successfully made a database via xampp, and exported the sql file into the database. I added the resource to my ACL's admin group I did these steps, and the connection was still unsuccessful, what did I do wrong? I really don't understand and I really appreciate any help, or suggestions to where to start to learn about these more, or just how to make a connection between the server and the database, thank y'all in advance!
  4. O que é? Pra que serve? Um banco de dados é onde ficam salvos diversos tipos de dados que são usados entre as sessões dos jogadores e do servidor, isto significa que mesmo se o jogador relogar no servidor ou até mesmo o servidor reiniciar, os dados salvos no banco de dados não são perdidos. (se o script que salvou lá foi feito corretamente). O que posso salvar neles? O MTA já cria 2 bancos de dados padrão quando vc cria seu servidor, são eles: internal.db - Onde são salvos todos os dados das contas dos jogadores, login, senha, grana do bolso, posição do jogador quando deslogou, vida, colete, skin, armas, munição, etc. registry.db - Onde são salvos todos os dados que são utilizados pelos resources, como por exemplo melhores pontuações das corridas (race gamemode), proprietários das casas, dados bancários dos jogadores, saldo bancário dos jogadores, carros comprados pelos jogadores, roupas compradas pelos jogadores, empresas adquiridas pelos jogadores, etc. Onde eles estão? Estes dois bancos de dados estão na pasta deathmatch do seu servidor, estão na linguagem SQLite. Você ainda pode criar outros bancos de dados externos, para serem usados pelos resources, mas na minha opinião isso não é recomendável, uma vez que vc usaria MySQL, que é mais complexo e exige certos cuidados de acesso e domínio, mas alguns servidores profissionais precisam fazer assim pois fizeram os bancos de dados ficarem fora do servidor em outro IP por segurança, dai é necessário ter bancos de dados externos. Nesse tutorial vamos tratar somente dos bancos de dados nativos do MTA, por serem mais fáceis de entender. Como mexo neles? Para salvar alguma coisa na conta do jogador, isto é, no internal.db, você usa setAccountData, e para obter esses dados depois, use getAccountData. É extremamente simples, funciona da mesma forma que um setElementData, mas em vez de salvar uma data temporária em um elemento, salva uma data permanente numa conta. Porém, para salvar alguma coisa no registry.db, é um pouco mais complicado, uma vez que vc vai precisar criar uma tabela nova para cada resource. Por exemplo, vc acabou de criar um resource de ranking por kills/deaths e você deseja salvar esse ranking no banco de dados para que ao reiniciar o resource ou o servidor, o ranking não seja perdido. Para isso vc vai precisar primeiramente criar uma tabela no banco de dados registry.db, essa tabela será acessada pelo resource, que irá salvar os dados dele lá. Para fazer qualquer coisa neste banco de dados (criar tabelas, inserir, alterar, remover, deletar, inserir colunas em determinada tabela, etc) vc vai precisar usar isso: executeSQLQuery. Aqui, será necessário conhecimento em SQL para fazer isso, mas é mais fácil do que aprender uma linguagem de programação nova, pois suas opções e sintaxes são menores do que uma linguagem inteira de programação, você não vai inventar nenhum sistema novo aqui, apenas criar e gerenciar tabelas e dados. Criar tabela nova no banco de dados: (o Caps Lock não é uma regra, mas é melhor para entender o que é código e o que é nome) [Os seguintes códigos só funcionam server-side] executeSQLQuery ("CREATE TABLE IF NOT EXISTS nomedatabela (nomecoluna1 TEXT, nomecoluna2 REAL, nomecoluna3 INTEGER)") TEXT = Valores desta coluna serão textos. Podem ter símbolos, números e espaços. REAL = Valores desta coluna serão numéricos reais. (números decimais, positivos, negativos e 0.0) INTEGER = Valores desta coluna serão numéricos inteiros. (positivos, negativos e 0) (não existe tipo BOOLEAN, use TEXT e insira valor "false" ou "true") (existe valor NULL, é diferente de vazio e diferente de 0. NULL significa ausência de dados. O NULL aparece quando você cria uma linha ou coluna nova sem atribuir valores a elas.) Deletar tabela do banco de dados: executeSQLQuery ("DROP TABLE nomedatabela") Todas as linhas, colunas, células e valores desta tabela são deletados junto. Deletar linhas da tabela: (as células não ficarão NULL) executeSQLQuery ("DELETE FROM nomedatabela WHERE colunaespecífica=?", valorDaCelulaEspecifica) O ? indica que o valor está após a declaração do SQL. Você poderia colocar o valor direto no lugar do ?. Mas por alguma razão, as vezes isso gera erro. Além disso, se o valor da célula estiver em uma variável no seu script, você não pode declarar a variável no lugar do ?. Ali só pode ser o valor direto, pois a declaração SQL inteira se trata de uma string. Por isso o uso do ?, que está recebendo o valor da variável que está depois da vírgula. Obs: Para verificar se uma célula tem valor nulo, não se usa os operadores lógicos de ==, <= >=. Para isso, usa-se IS NULL ou IS NOT NULL. Ex: executeSQLQuery ("DELETE nomecoluna1,nomecoluna2 FROM nomedatabela WHERE nomecoluna3 IS NULL") Isso vai deletar todas as células da coluna 1 e coluna 2 onde a coluna 3 tem uma célula de valor NULL. Se a coluna 3 não tiver nenhuma célula de valor NULL, nada acontece. Inserir nova linha de valores: (ele vai criar automaticamente uma nova linha com novas células) executeSQLQuery ("INSERT INTO nomedatabela(nomecoluna1,nomecoluna2,nomecoluna3) VALUES(?,?,?)", valorCelulaColuna1, valorCelulaColuna2, valorCelulaColuna3) Neste caso, ele está inserindo 3 novos valores, cada valor em uma coluna. Se você não declarar os nomes das colunas, ele vai preencher na ordem das colunas automaticamente. Você pode deixar de declarar uma coluna se não quiser atribuir valor na célula daquela coluna. Se o tipo de valor da variável não for do tipo de dado daquela coluna, dará erro. Atualizar valores de células que já existem em uma tabela: (não é possível alterar os tipos de valores, é necessário editar o tipo da coluna se quiser fazer isso) executeSQLQuery ("UPDATE nomedatabela SET nomecoluna2=?,nomecoluna3=? WHERE nomecoluna1=?", valorCelulaColuna2, valorCelulaColuna3, valorCelulaColuna1) No caso acima, ele vai atualizar as células das colunas 2 e 3 onde o valor da célula da coluna 1 for igual ao valor de valorColunaCelula1. OBS: Nada impede que você coloque as primeiras variáveis junto à declaração SQL, mas para fazer isso você deve "cortar" a string, inserir as variáveis e depois continuar a string, Ex: executeSQLQuery ("UPDATE nomedatabela SET nomecoluna2= '".. valorCelulaColuna2 .."',nomecoluna3='".. valorCelulaColuna2 .."' WHERE nomecoluna1=?", valorCelulaColuna1) Lembrando que o valor destas variáveis também são strings na declaração, portanto use aspas simples antes e depois de cada corte para transformar os valores em string. Os dois pontos (..) significam que estes valores fazem parte do argumento SQL. Da mesma forma, se vc usar "1" .. "1", será igual a "11". (Por isso acho muito mais fácil deixar tudo ? na declaração SQL e colocar as variáveis todas após a string.) Selecionar determinadas células da tabela: (usado geralmente para obter os valores destas células para usar no script, você pode selecionar somente 1 célula ou várias) executeSQLQuery ("SELECT nomecoluna1,nomecoluna2 FROM nomedatabela WHERE nomecoluna3=?", valorCelulaColuna3) Neste exemplo, ele vai selecionar a célula da coluna 1 e a célula da coluna 2, na linha onde a célula da coluna 3 for igual a valorCelulaColuna3. Alterar a tabela (adicionar coluna nova) [SQLite não suporta deletar coluna nem editar tipo de coluna] executeSQLQuery ("ALTER TABLE nomedatabela ADD nomecoluna4 REAL") Devido a limitações do SQLite, ALTER TABLE não pode ser usado para deletar uma coluna nem para editar seu tipo. Para fazer isso é necessário recriar a tabela inteira com as novas alterações. No exemplo acima, ele vai adicionar uma nova coluna chamada "nomecoluna4". Tá, mas como ficaria tudo isso dentro de um script? Fiz um código com vários testes de banco de dados. Cada comando faz alguma coisa. É possível mexer em um banco de dados manualmente sem usar scripts? Sim, é possível. Eu mesmo costumo fazer isso para corrigir algumas coisas rápidas sem precisar programar mais nada. Para poder abrir os bancos de dados (internal.db e registry.db) você deve usar um programa chamado DB Browser for SQLite. Um programa gratuito, leve e bem fácil de entender. Nele você consegue acessar todas as tabelas do banco de dados e editar os valores como se fosse em uma planilha do Excel. Basta ir na aba Navegar dados, selecionar a tabela que deseja modificar, clicar em cima da célula cujo valor deseja atualizar, digitar o novo valor, clicar em Aplicar e depois clicar em Escrever modificações (salvar banco de dados). Pronto! E tem mais! Se você já tiver conhecimento avançado com a linguagem SQL, você também pode fazer alterações avançadas via código dentro do programa. Basta acessar a aba Executar SQL, escrever o comando SQL corretamente e depois clicar no botão de Play. Espero ter ajudado.
  5. Yesterday evening, I started my apprenticeship with db, I always wanted to learn, because with it, I can do mods, which I could not do without. My introduction with Database was done by adapting a System ID to the DB in the login panel. I did this using the server-side of my login panel. The first thing we do, is to use dbConnect (Wiki), which will make the connection to the db file. local db = dbConnect("sqlite", "db/royalusers.db") It will create the "db" folder, in the resource files, and inside the folder, the "royalusers.db" file. After that, we create a table using the SQL functions. local newTable = dbExec(db, "CREATE TABLE IF NOT EXISTS RoyalUsers (id INT, name TEXT, login TEXT, pass TEXT, serial TEXT)") RoyalUsers - Table-name id INT, name TEXT, login TEXT, pass TEXT, serial TEXT - columns of the table. INT - INTERNAL NUMBER Now the part of using the table defined in the database. function registerPlayer(user, pass, conf) if user == "" then outputLoginMsg(source, "Preencha todos os campos!", "error") else if pass == "" then outputLoginMsg(source, "Preencha todos os campos!", "error") else if conf == "" then outputLoginMsg(source, "Preencha todos os campos!", "error") else if conf == pass then addAccount(tostring(user),tostring(pass)) triggerClientEvent(source, "onRoyalRegister", source) local query = dbPoll(dbQuery(db, "SELECT * FROM RoyalUsers WHERE login=?", user),-1) if #query == 0 then dbExec(db, "INSERT INTO RoyalUsers VALUES (?, ?, ?, ?, ?)", countIDs(), getPlayerName(source), user, pass, getPlayerSerial(source)) end outputLoginMsg(source, "Conta criada com sucesso! Aguarde...", "success") if not getAccount(user, pass) then outputLoginMsg(source, "Esta conta já está sendo utilizada!", "error") end else outputLoginMsg(source, "As senhas não estão iguais.", "error") end end end end end addEvent("onPlayerRequestRegister", true) addEventHandler("onPlayerRequestRegister", root, registerPlayer) function countIDs() local table = dbPoll(dbQuery(db, "SELECT * FROM RoyalUsers"), -1) local count = 1 for i, result in pairs(table) do count = count + 1 end return count end The login variable returns a table, it selects (SELECT) all the columns of the table, and checks if the login defined in the function does not exist in it, if it does not exist, it will add those information, the columns of the table RoyalUsers (INSERT INTO). VALUES (?, ?, ?, ?, ?) - "?" It is the amount of arguments that will be used to insert into the column. countIDs() - Function that returns the number of IDs in the table, and adds one more. getPlayerName(source) - Gets the player's name, and adds the "name" column of the table. user - Adds the user defined in the function, the column "login". pass - Adds the password set in the function, the "pass" column. getPlayerSerial(source) - Gets the player's serial, and adds the "serial" column of the table. Having the part in which the data that the player registers, are saved in the database, this part is ready. Now, just set the ID added to the database login, when the player logs in. function loginPlayer(source, user, pass) if user == "" then outputLoginMsg(source, "Preencha todos os campos!", "error") else if pass == "" then outputLoginMsg(source, "Preencha todos os campos!", "error") else local account = getAccount(user, pass) if account then logIn(source, account, pass) local queryTable = dbPoll(dbQuery(db, "SELECT * FROM RoyalUsers WHERE login='"..getAccountName(getPlayerAccount(source)).."'"), -1) for i, id in pairs(queryTable) do setElementData(source, "ID", id["id"]) end setTimer(setCameraTarget, 3000, 1, source, source) setTimer(triggerClientEvent, 14000, 1, source, "renderRoyalID", source) triggerClientEvent(source, "onRoyalLogin", source) outputLoginMsg(source, "Logado com sucesso! Aguarde...", "success") else outputLoginMsg(source, "Usuário ou senha incorretos!", "error") end end end end addEvent("onPlayerRequestLogin", true) The queryTable gets all the columns of the table, where the login = login of the player. After that, we loop the tables returned by the queryTable, and set the date "ID" to the player, according to the ID returned from the table defined in the loop. I want to make it clear that the tutorial did not go well explained, I just want to share, what I learned yesterday, and if I did something wrong, please let me know.
  6. Boa noite. Eu queria "excluir" todos os IDs registrados no servidor sem precisar desligar o servidor !! retornando os números de IDs para voltar a contar os IDs do 1 !! preciso de ajuda com isso URGENTE !!
  7. Bom eu tenho um arquivo database.db cheio de tabelas (Player, CNH, Vehicles, Garagem, sqlite_sequence e outros) para meu servidor porém queria que meus scripts fossem salvos nele. Ele ja tem o meta, o sever.Lua etc, mas não sei como por para meus scripts salvarem nele em si, se alguém souber como é possível realizar isso e estar me respondendo agradeço desde já. (Ele é SQLite)
  8. tenho dois scripts um de garagem e outro de compra de carros que usam data base "dbpoll", após fazer testes no servidor local comprando vários carros. quando coloco esses Mods no meu oficial ele aparece os carros que comprei no teste, queria saber como reinicio ou apago todos os dados pra poder usufruir dos Mods livremente. desde já agradeço.
  9. can anyone please send me and Database file/script for a dayz server or a video how i can make it cose im new to making servers and i realy don't understand anything
  10. Olá pessoal, boa tarde! Faz tempo que tenho um conhecimento relativamente avançado em Lua e MTA Scripting, porém não sabia absolutamente NADA em relação á banco de dados SQLite. Há pouco tempo atrás aprendi sobre, porém preciso de ajuda com o seguinte problema: » Preciso salvar no banco de dados, a cada vez que um comando é efetuado, salvar +1 número na célula da coluna... Deu pra entender? Tipo assim: Carro Estoque Camaro 1 Quando eu efetuar o comando: Carro Estoque Camaro 1 +1 *eu preciso pegar o valor existente na coluna e somar 1, porém estou com problemas para fazer haha *Não postei meu código pois simplesmente não consegui fazer um... hahah
  11. eu estou tentando programar um trabalho de leiteiro utilizando um inventario, e pra isso estou utilizando uma data base em uma host, a minha ideia pro trabalho do leiteiro é que primeiro o player tem que comprar um balde, depois ele tem que ir até uma vaca e tirar o leite dela, com isso o balde vazio é removido do inventario do player e um cheio é adicionado. só que tem um problema, se o player não tiver comprado o balde e executar o comando, ele irá conseguir tirar o leite da vaca do mesmo jeito, não tenho muita experiencia com MySQL aliás quase nenhuma, essa é a minha primeira vez A foto abaixo é da data base e do que fica armazenado no tabela de items do inventario na minha host:
  12. Fala pessoal,baixei um mod de RG onde tem a opção de se colocar o nome completo,eu queria q esse nome fosse para o nink do jogador quando escrevesse no chat.Tenho uma pequena noção sobre database
  13. Hi, I've started writing scripts connected to the database, and I struggle why the current script that I am working on doesn't work. Info: - Name of the table: accounts - Columns: username, skin, money - No errors Here is my script: function showStats(player) local playerName = getPlayerName(player) local qh = dbQuery(db, "SELECT skin, money FROM accounts WHERE username=?", playerName) local result = dbPoll(qh, -1) if result then for _, row in ipairs(result) do outputChatBox("Skin: " ..row["skin"].. "Money: "..row["money"] .. "") end end end addCommandHandler("stats", showStats)
  14. Olá, eu estou desenvolvendo um código e me vi a necessidade de usar uma database, porém não entendo nada do assunto, eu andei dando uma lida no tutorial do @Lord Henry porém não entendi como por cada coisa em pratica; O que eu quero fazer: Uma Loja de Skins, que a mesma tem um botão de usar, na hora que ele apertar o botão de Comprar, se ele já tiver a Skin comprada, aparece uma mensagem para apertar no outro botão (Botão de usar a Skin), porém estou em dúvidas nessa parte de obter se ele tem a skin... Enfim, na Database em Geral. Se pudessem me ajudar ficaria agradecido function DeltaSCR_Comprar (_, state) if DeltaSCR_Painel == true then if state == "down" then if isCursorOnElement (screenW * 0.5295, screenH * 0.5583, screenW * 0.1094, screenH * 0.0500) then -- //CANCELAR DeltaSCR_Abrir () elseif isCursorOnElement (screenW * 0.5295, screenH * 0.4917, screenW * 0.1094, screenH * 0.0500) then -- //USAR elseif isCursorOnElement (screenW * 0.5295, screenH * 0.4250, screenW * 0.1094, screenH * 0.0500) then -- //COMPRAR local rowItem = guiGridListGetSelectedItem (skinsList) if rowItem ~= -1 then if guiGridListGetItemText (skinsList, rowItem, 1) == "Skin 1" then setElementModel (localPlayer, 0) takePlayerMoney (300) DeltaSCR_Abrir () elseif guiGridListGetItemText (skinsList, rowItem, 1) == "Skin 2" then setElementModel (localPlayer, 1) takePlayerMoney (300) DeltaSCR_Abrir () elseif guiGridListGetItemText (skinsList, rowItem, 1) == "Skin 3" then setElementModel (localPlayer, 2) takePlayerMoney (300) DeltaSCR_Abrir () elseif guiGridListGetItemText (skinsList, rowItem, 1) == "Skin 4" then setElementModel (localPlayer, 7) takePlayerMoney (300) DeltaSCR_Abrir () elseif guiGridListGetItemText (skinsList, rowItem, 1) == "Skin 5" then setElementModel (localPlayer, 9) takePlayerMoney (300) DeltaSCR_Abrir () elseif guiGridListGetItemText (skinsList, rowItem, 1) == "Skin 6" then setElementModel (localPlayer, 10) takePlayerMoney (300) DeltaSCR_Abrir () elseif guiGridListGetItemText (skinsList, rowItem, 1) == "Skin 7" then setElementModel (localPlayer, 11) takePlayerMoney (300) DeltaSCR_Abrir () elseif guiGridListGetItemText (skinsList, rowItem, 1) == "Skin 8" then setElementModel (localPlayer, 12) takePlayerMoney (300) DeltaSCR_Abrir () end end end end end end addEventHandler ("onClientClick", getRootElement(), DeltaSCR_Comprar)
  15. Hi, I want to know what is the mass of the mta server. Player using /register Oi, Eu queria saber onde fica os logins e register dos players, Qual pasta. Dos players que usou /register
  16. Olá pessoas deliciosamente bonitas! Bom, estou desenvolvendo um save-system por SQLite, porém, na parte de salvar as coordenadas do jogador, do contrário de salvar cada um dos tipos de coordenadas em uma coluna (X - Y - Z) eu queria salvar em uma única coluna (Coordenadas), mas como vocês devem saber, dados obtidos de um db são retornados como string, então utilizei Vector3 e tonumber, mas com o tonumber retorna um valor nulo, e sem ele retorna uma string, como eu poderia fazer para retornar o valor original de coordenadas? Código: local x2, y2, z2 = 675.99396,-1692.27075,8.70498 -- LUGAR QUE VAI SPAWNAR QUANDO CRIAR CONTA NOVA local db = exports.ds_sqlite db:exec("CREATE TABLE IF NOT EXISTS Usuarios (Nick TEXT, Usuario TEXT, Serial TEXT, Skin INT, Dinheiro INT, Coordenadas TEXT, Interior INT, Dimensao INT, Procurado INT)") function loadUsuarios(player, acc) local accName = getAccountName(getPlayerAccount(player)) local datas = db:query("SELECT * FROM Usuarios WHERE Usuario=? LIMIT 1", accName) if (datas and type(datas) == "table" and #datas > 0) then -- @Datas setElementData(player, "CRP:Skin", tonumber(datas[1]["Skin"])) setElementData(player, "CRP:Dinheiro", tonumber(datas[1]["Dinheiro"])) setElementData(player, "CRP:Coordenadas", datas[1]["Coordenadas"]) setElementData(player, "CRP:Interior", tonumber(datas[1]["Interior"])) setElementData(player, "CRP:Dimensao", tonumber(datas[1]["Dimensao"])) setElementData(player, "CRP:Procurado", tonumber(datas[1]["Procurado"])) iprint(datas[1]["Coordenadas"]) -- @Funções setCameraTarget(player, player) fadeCamera(player, true, 2.0) spawnPlayer(player, Vector3(datas[1]["Coordenadas"])) setElementPosition(player, Vector3(datas[1]["Coordenadas"])) setElementModel(player, tonumber(datas[1]["Skin"])) setPlayerMoney(player, tonumber(datas[1]["Dinheiro"])) setElementInterior(player, tonumber(datas[1]["Interior"])) setElementDimension(player, tonumber(datas[1]["Dimensao"])) setPlayerWantedLevel(player, tonumber(datas[1]["Procurado"])) else setCameraTarget(player, player) fadeCamera(player, true, 2.0) spawnPlayer(player, x2, y2, z2) setElementPosition(player, x2, y2, z2) local x, y, z = getElementPosition(player) db:exec("INSERT INTO Usuarios VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)", getPlayerName(player):gsub("#%x%x%x%x%x%x", ""), accName, getPlayerSerial(player), getElementModel(player), getPlayerMoney(player), x..","..y..","..z + 0.7, getElementInterior(player), getElementDimension(player), getPlayerWantedLevel(player)) end end function saveUsuarios(player, acc) local accName = getAccountName(getPlayerAccount(player)) local datas = db:query("SELECT * FROM Usuarios WHERE Usuario=? LIMIT 1", accName) if (#datas > 0) then local x, y, z = getElementPosition(player) db:query("UPDATE Usuarios SET Nick=?, Usuario=?, Serial=?, Skin=?, Dinheiro=?, Coordenadas=?, Interior=?, Dimensao=?, Procurado=?", getPlayerName(player):gsub("#%x%x%x%x%x%x", ""), accName, getPlayerSerial(player), getElementModel(player), getPlayerMoney(player), x..","..y..","..z + 0.7, getElementInterior(player), getElementDimension(player), getPlayerWantedLevel(player)) end end addEventHandler("onPlayerLogin", root, function() for index, players in ipairs(getElementsByType("player")) do if (players == source) then local account = getPlayerAccount(players) loadUsuarios(players, account) end end end ) addEventHandler("onPlayerQuit", root, function() for index, players in ipairs(getElementsByType("player")) do if (players == source) then local account = getPlayerAccount(players) if (account) then saveUsuarios(players, account) end end end end )
  17. -- This piece of code in located in the 'onPlayerQuit' event handler. It saves the player's weapons and ammo if he has any, this is all working correctly local weapons = {} for slot = 1, 12 do local weapon = getPedWeapon(source, slot) if weapon > 0 then local ammo = getPedTotalAmmo(source, slot) if ammo > 0 then table.insert(weapons, {weapon, ammo}) end end end -- This is what appears under the 'weapons' column in the player's account table entry [ [ [ 30, 176 ] ] ] -- Which means the player left the server and had an AK-47 with total 176 ammo left -- And this is the part which loads the SQL weapons data for weapon, ammo in ipairs(fromJSON(accountData.weapons)) do giveWeapon(player, tonumber(weapon), tonumber(ammo)) end -- The problem is, the player doesn't get the weapons he has saved, instead, he'll be given a brassknuckle everytime and the SQL entry is reset Any ideas why it is not working properly? I'm using SQLite not MySQL. The weapons are saved correctly, so it would seem that the problems stems in the loading part.
  18. I have a function that gets the information of all the cars that has been bought for ingame money and it can spawn the cars when the resource is started but when a player disconnects and the vehicle data is changed when the player reconnects he is not able to see the changes to the car as I looked over other scripts they only using server side. This is the only function that gets the vehicles data from the database but it only does when the resource starts function spawnAllCars() local query = mysql:query("SELECT * FROM vehicles") local rows = mysql:fetch_assoc(query) if rows then while true do local veh = nil local rows = mysql:fetch_assoc(query) if not rows then break end if tonumber(rows["locX"]) ~= 0 and tonumber(rows["locY"]) ~= 0 and tonumber(rows["locZ"]) ~= 0 and tonumber(rows["rotX"]) ~= 0 and tonumber(rows["rotY"]) ~= 0 and tonumber(rows["rotZ"]) ~= 0 then local veh = createVehicle(tonumber(rows["modelID"]), rows["locX"], rows["locY"], rows["locZ"], rows["rotX"], rows["rotY"], rows["rotZ"]) else local veh = createVehicle(tonumber(rows["modelID"]), rows["spawnLocX"], rows["spawnLocY"], rows["spawnLocZ"], rows["spawnRotX"], rows["spawnRotY"], rows["spawnRotZ"]) end setVehColor(veh, rows["color1"], rows["color2"], rows["color3"], rows["color4"]) setElementHealth(veh, rows["damage"]) setElementInterior(veh, tonumber(rows["interior"])) setElementDimension(veh, tonumber(rows["dimension"])) table.insert(vehTable, {["id"] = rows["id"], ["health"] = rows["damage"]}) end end end addEventHandler("onResourceStart", getResourceRootElement(), spawnAllCars) Do I need to add something in client side or just need to change something in this?
  19. Hi, I want a good way to learn database functions and sql, i really had many problems in my scripts without a database, so i want to be pro in database scripting. So pls if u have a good way tell me
  20. Hello guys, if there was too many resources uses a private database (dbConnect), Would that going to cause a problem ?, Like losing connection on some other resources or something ?
  21. What I wanted to do, was that the user to buy a certain accessory color and object, that is saved and at the beginning, not only can see it, but also can see others. Server: function Cortina1(paintjobID, color) local vehicle = getPedOccupiedVehicle( client ) local player = client if ( vehicle ) then local pos = {getElementPosition( vehicle )} Cortinapuesta = createObject( 1000, pos[1], pos[2], pos[3] ) attachElements( Cortinapuesta, vehicle, 0, 0, 0, 0, 0, 0 ) triggerClientEvent (root, "setShader", resourceRoot, paintjobID, color) end end addEvent("PonerCortina", true) addEventHandler("PonerCortina", resourceRoot, Cortina1) function CancelarCortina() local vehicle = getPedOccupiedVehicle( source ) if ( vehicle ) then destroyElement(Cortinapuesta) end end addEvent("SacarCortina", true) addEventHandler("SacarCortina", root, CancelarCortina) ----------------------------------------------------------------------------------------------------- function addPJfction (player) triggerClientEvent (getRootElement(),"addPJ2", getRootElement(), player ) end addEvent( "addPJ", true ) addEventHandler( "addPJ", resourceRoot, addPJfction ) function removePJfction (player) triggerClientEvent (getRootElement(),"removePJ2", getRootElement(),player ) end addEvent( "removePJ", true ) addEventHandler( "removePJ", resourceRoot, removePJfction ) Client: Ventana1 = createMarker (2194.4677734375, 1440.5966796875, 10.8203125-1, "cylinder", 1.5, 0, 255, 0, 170 ) local NormalTextColour = "FFFB0202" function mapLoad ( Bondi2018OBJETOS ) local txdCortinas1518 = engineLoadTXD( "objetos/metalpar1518/vehicle.txd" ) local dffCortinas1518 = engineLoadDFF( "objetos/metalpar1518/spl_b_mar_m.dff", 0 ) engineImportTXD( txdCortinas1518, 1000 ) engineReplaceModel( dffCortinas1518, 1000 ) end addEventHandler ( "onClientResourceStart", resourceRoot, mapLoad ) addEventHandler("onClientMarkerHit", Ventana1, function(localPlayer) if localPlayer == getLocalPlayer() then Ventana = guiCreateWindow(997, 226, 228, 743, "BONDI 2018 - Taller \"Libertad\"", false);guiSetVisible(Ventana, true) guiWindowSetSizable(Ventana, false) guiSetProperty(Ventana, "CaptionColour", "FF0EF1E3") showCursor(true) veh = getPedOccupiedVehicle( localPlayer ) Boton1 = guiCreateButton(15, 66, 108, 31, " CORTINAS", false, Ventana); guiSetProperty(Boton1, "NormalTextColour", "FFFB0202") Boton2 = guiCreateButton(15, 107, 108, 31, " Parachoques", false, Ventana);guiSetProperty(Boton2, "NormalTextColour", "FFFB0202") Boton3 = guiCreateButton(15, 148, 108, 31, " ASIENTOS", false, Ventana);guiSetProperty(Boton3, "NormalTextColour", " FFFB0202") Boton4 = guiCreateButton(15, 189, 108, 31, " VIDRIOS", false, Ventana);guiSetProperty(Boton4, "NormalTextColour", "FFFB0202") Boton5 = guiCreateButton(15, 230, 108, 31, " OPTICAS", false, Ventana);guiSetProperty(Boton5, "NormalTextColour", "FFFB0202") Boton6 = guiCreateButton(15, 271, 108, 31, "", false, Ventana);guiSetProperty(Boton6, "NormalTextColour", " FFFB0202") Boton7 = guiCreateButton(15, 312, 108, 31, "", false, Ventana);guiSetProperty(Boton7, "NormalTextColour", " FFFB0202") Boton8 = guiCreateButton(15, 353, 108, 31, "", false, Ventana);guiSetProperty(Boton8, "NormalTextColour", " FFFB0202") Boton9 = guiCreateButton(15, 394, 108, 31, "", false, Ventana);guiSetProperty(Boton9, "NormalTextColour", " FFFB0202") BotonCERRAR = guiCreateButton(15, 700, 108, 31, "CERRAR", false, Ventana);guiSetProperty(BotonCERRAR, "NormalTextColour", "FFFB0202") end end ) Ventana2 = guiCreateWindow(997, 226, 228, 743, "BONDI 2018 - Taller \"Libertad\"", false);guiSetVisible(Ventana2, false);guiWindowSetSizable(Ventana2, false);guiSetProperty(Ventana2, "CaptionColour", "FF0EF1E3") Boton1 = guiCreateButton(60, 66, 108, 31, "Cortinas Simples", false, Ventana2); guiSetProperty(Boton1, "NormalTextColour", "FFFB0202") Boton2 = guiCreateButton(15, 107, 108, 31, " Turquesas", false, Ventana2);guiSetProperty(Boton2, "NormalTextColour", "FFFB0202") Boton2b = guiCreateMemo(150, 107, 64, 31, "2500", false, Ventana2); guiSetProperty(Boton2b, "NormalTextColour", "FFFB0202");guiMemoSetReadOnly( Boton2b, true ) Boton3 = guiCreateButton(15, 148, 108, 31, " 2", false, Ventana2);guiSetProperty(Boton3, "NormalTextColour", " FFFB0202"); Boton4 = guiCreateButton(15, 189, 108, 31, " 3", false, Ventana2);guiSetProperty(Boton4, "NormalTextColour", "FFFB0202") Boton5 = guiCreateButton(15, 230, 108, 31, " 4", false, Ventana2);guiSetProperty(Boton5, "NormalTextColour", "FFFB0202") Boton6 = guiCreateButton(15, 271, 108, 31, "5", false, Ventana2);guiSetProperty(Boton6, "NormalTextColour", " FFFB0202") Boton7 = guiCreateButton(15, 312, 108, 31, "6", false, Ventana2);guiSetProperty(Boton7, "NormalTextColour", " FFFB0202") Boton8 = guiCreateButton(60, 353, 108, 31, "Cortinas Completas", false, Ventana2);guiSetProperty(Boton8, "NormalTextColour", " FFFB0202") Boton9a = guiCreateButton(15, 394, 108, 31, "Turquesas", false, Ventana2);guiSetProperty(Boton9a, "NormalTextColour", " FFFB0202") Boton10a = guiCreateButton(15, 435, 108, 31, "Rojas", false, Ventana2);guiSetProperty(Boton10a, "NormalTextColour", " FFFB0202") Boton11a = guiCreateButton(15, 476, 108, 31, "Azules", false, Ventana2);guiSetProperty(Boton11a, "NormalTextColour", " FFFB0202") Boton12a = guiCreateButton(15, 517, 108, 31, "Blancas", false, Ventana2);guiSetProperty(Boton12a, "NormalTextColour", " FFFB0202") Boton13a = guiCreateButton(15, 558, 108, 31, "Celestes", false, Ventana2);guiSetProperty(Boton13a, "NormalTextColour", " FFFB0202") BotonTOTAL = guiCreateMemo (15, 650, 60, 31, "Total:", false, Ventana2);guiSetProperty(BotonTOTAL, "NormalTextColour", "FFFB0202");guiMemoSetReadOnly( BotonTOTAL, true ) BotonTOTAL2 = guiCreateMemo (75, 650, 60, 31, "0", false, Ventana2);guiSetProperty(BotonTOTAL2, "NormalTextColour", "FFFB0202");guiMemoSetReadOnly( BotonTOTAL2, true ) BotonCOMPRAR = guiCreateButton (135, 650, 65, 31, "COMPRAR", false, Ventana2);guiSetProperty(BotonCOMPRAR, "NormalTextColour", "FFFB0202") BotonCERRAR2 = guiCreateButton(15, 700, 108, 31, "CERRAR", false, Ventana2);guiSetProperty(BotonCERRAR2, "NormalTextColour", "FFFB0202") addEventHandler("onClientGUIClick", guiRoot, --VENTANA function() local getGui = guiGetVisible(Ventana) if source == BotonCERRAR then if getGui then guiSetVisible(Ventana, false) showCursor(false) veh = getPedOccupiedVehicle( localPlayer ) end end end ) -------------------------------------------------------------------------------------------- --------------------------------------------------------------------------------------------- ------------------------------------------------------------------------------------------- addEventHandler("onClientGUIClick", guiRoot, --VENTANA function() local getGui = guiGetVisible(Ventana2) if source == BotonCERRAR2 then if getGui then guiSetVisible(Ventana2, false) showCursor(false) veh = getPedOccupiedVehicle( localPlayer ) triggerServerEvent("SacarCortina", localPlayer, localPlayer) end end end ) addEventHandler("onClientGUIClick", guiRoot, --VENTANA2 = CORTINAS function() local getGui = guiGetVisible(Ventana) if source == Boton1 then if getGui then guiSetVisible(Ventana, false) guiSetVisible(Ventana2, true) veh = getPedOccupiedVehicle( localPlayer ) end end end ) --------------------------------------------------------------------------------------------------------- addEventHandler("onClientGUIClick", guiRoot, --VENTANA2 = CORTINAS > Completas > Turquesas function () local getGui = guiGetVisible(Ventana2) if source == Boton9a then local color = "nada" triggerServerEvent("PonerCortina", resourceRoot, paintjobID, color) PrecioCortinasCompletas = 3500 PrecioTotal = PrecioCortinasCompletas guiSetText(BotonTOTAL2, PrecioCortinasCompletas) else if source == Boton10a then --ROJAS local color = "red" triggerServerEvent("PonerCortina", resourceRoot, paintjobID, color) PrecioCortinasCompletas = 3500 PrecioTotal = PrecioCortinasCompletas guiSetText(BotonTOTAL2, PrecioCortinasCompletas) end end end ) addEvent( "addPJ2", true ) addEventHandler( "addPJ2", getLocalPlayer(), CortinasCompletas ) function addPaintjob2(paintjobID, color) outputChatBox("the color is:" .. color) if color == "red" then CortinasRojas = dxCreateTexture ( "CortinasRojas.png" ) engineRemoveShaderFromWorldTexture (shader_cars,"cortinas", getPedOccupiedVehicle ( player )) shader_cars , tec = dxCreateShader ( "shader.fx" ) engineApplyShaderToWorldTexture (shader_cars,"cortinas", getPedOccupiedVehicle ( player )) dxSetShaderValue (shader_cars,"TX0",CortinasRojas) elseif color == "blue" then CortinasAzules = dxCreateTexture ( "CortinasAzules.png" ) engineRemoveShaderFromWorldTexture (shader_cars,"cortinas", getPedOccupiedVehicle ( player )) shader_cars , tec = dxCreateShader ( "shader.fx" ) engineApplyShaderToWorldTexture (shader_cars,"cortinas", getPedOccupiedVehicle ( player )) dxSetShaderValue (shader_cars,"TX0",CortinasAzules) elseif color == "Nada" then outputChatBox ("Asi como está") end end addEvent( "setShader", true ) addEventHandler( "setShader", resourceRoot, addPaintjob2 ) -------------------------------------------------------------------------------------- addEventHandler("onClientGUIClick", guiRoot, --VENTANAS > BOTON COMPRAR function(localPlayer) local getGui = guiGetVisible(Ventana2) local money = getPlayerMoney (localPlayer) if source == BotonCOMPRAR then if (money > PrecioTotal) then outputChatBox ("Dinero CALCULADO") takePlayerMoney ( PrecioTotal ) outputChatBox ("Usted ha comprado las cortinas") guiSetVisible(Ventana2, false) showCursor (false) else outputChatBox ("No tiene el dinero suficiente para comprarlas!!") end end end)
  22. im running a project and im facing some problems in Database i might need some help contact me on Discord : SnowBOxx®#4050
  23. صورة المشكلة بتمنا تلاقولي حل
  24. So, friend of mine got this error: Picture He was like: dbConnection was in use, this is why it happened, but i was like: thats impossible, so this is why i ask you guys. btw: This is just a question, and i dont need a script-fix for is, just an answer about it.Thx in advance.
×
×
  • Create New...