Search the Community
Showing results for '{query}'.
Found 91 results
-
My function DBSelect function DBSelect(query) { if(query == undefined) { console.log("Not definied query"); } else { handler.query(query, function(error, result) { if(error) { console.log("Error " + error); throw error; } return result; }); } } And whitelist script "use strict" const mysql = require("./database"); mp.events.add("playerJoin", function(player) { const check = mysql.DBSelect("SELECT * FROM whitelist WHERE socialID='" + player + "';"); if(check == 0) { player.kick("Kick reason"); console.log("sadsad"); } }); Console dont show any errors, in join in server and dont kick me
-
function MysqlName(sqlid, cb) { iHandle.mysql.handle.query("SELECT `Username` FROM `accounts` WHERE `UserID`= ?", [sqlid], function (err, rows, fields) { if (err) throw err; cb(rows[0].Username); }); } var qwf = null; MysqlName(19, function (name) { qwf = name; console.log("returning name: " + name) // return Firstname_Lastname (its ture) } ); console.log(qwf); // RESULT NULL I did a function to pull the user name from the database. I can't assign it to global value. A very interesting mistake. How can I solve this?
-
Thank you. I typed a much more specific query, and I didn't find that. Also, from what I can see, that issue was never confirmed to be a bug in .NET Core. The issue was moved elsewhere, and it was never reproduced and proven to be a bug--again, as far as I can see. And as I pointed out in my original post, I couldn't reproduce it in .NET Core 2.0, 2.1, or 2.2. But since the author of Wired Players, Xabi, has elsewhere said to rename .resx files to force it work for your culture, that's what I'm doing for now. Thanks again.
-
Hello, I want to create an inventory system. mp.events.addCommand("inventory", (player) => { gm.mysql.handle.query('SELECT * FROM items', [], function (error, results, fields) { for(let i = 0; i < results.length; i++) { if(results[i].owner == player.name) { player.call("Inv", [player,results[i].name); player.call("Inventory", [player, "test"]); } } }); }); This is the Command to call the Inventory. And this the Inventory: mp.events.add({ "Inv": (player,name) => { inventory.AddItem(Inv = new UIMenuItem(""+name,"")); } }); Every time I go to the menu, the same menu items are created again. Have anyone a solution? Thanks. Greetings Boomray
-
I am using the following code: var SQL = require('mysql') var c = SQL.createConnection({ host: '*here was my ip*', user: '*here was my user*', password: '*here was my password*', database: '*here was my database*' }); console.log("TESTTESTTEST"); c.connect(function(e) { console.log(123); if(e) { console.log("Error connecting to the database with error "+e); } else { console.log('Database connected!') } }); c.query("INSERT INTO Cars VALUES (5,5,5,5,123)") c.query("SELECT * FROM Cars", (err, result) => { console.log(result); }); and it doesnt work when I run it as a part of server package, but works well when I run it with Node. Please, help me.
-
There's no need to use that query anymore, did you find it anywhere on the tutorial?
-
Well yeah, where is ‘player’ defined for player.name to work? You can’t get a player object out of thin air. Considering the query isn't in an event or anything, how can it get a players name if nobody is even connected? All that code not sitting inside an event is being ran as soon as the server starts
-
Hey guys, iam pretty new to C# and dont know, how to connect to my MySQL database and do a simple select query. It would be awesome, if a person could post a simple connect and select programm code, so I can work with it, and understand how to do it. Thank you in advance.
-
hey guys, i'm new to ragemp and javascript. i use node. how is it possible to use my mysql connection from other files? Like database.js my code where i want the connection of database: "use strict" const datab = require('../Database'); const List = []; connection.query("SELECT * FROM `table`", function(error, result) { if(error) { throw error; } else { console.log('Result is '+result[0].uName); } }); i want to load my whole table to the List
-
Hello, My script used to connect to my remote hosted DB fine in V0.3.5. However, since updating to V0.3.6+ I can only connect to my localhost. This is the only code in my packages: var mysql = require('mysql'); console.log('conn'); var conn = mysql.createConnection({ host: 'MY_REMOTE_IP', user: 'MY_REMOTE_USR', debug: true, password: 'MY_REMOTE_PW', database: 'MY_REMOTE_DB', supportBigNumbers: true }); conn.connect(function (err) { console.log('Got connected'); }); conn.query('SELECT * from accounts', function (error, results, fields) { if (error) console.log(error); console.log('account ', results[0]); }); The host says the DB is configured fine (host is a Game Server host) and it must be NodeJS or Rage. However when I run the above index.js from terminal I get connection and even the rows in the database. I see that V0.3.6 had some NodeJS adjustments, security enhancements and V8. I've installed the latest NPM, NodeJS and mysql JS package. The host refers me to Rage, mysql JS community refers me to the DB host. What can I do?
-
Hi there, I am having a bit of trouble with making a faction through a CEF system, I have followed several tutorials also how to debug the CEF but it didn't work till now so I decided to post it here In the client_package folder I have: var openedConsole = false; let loginBrowser; let displayFactionDialoge = (player_ID) => { loginBrowser = mp.browsers.new("package://faction/createfaction.html"); mp.gui.cursor.show(true, true); openedConsole = true; }; mp.events.add("SendFactionCreateData", (user, pass, state) => { mp.gui.chat.push("SendFactionCreateData - has been activated"); mp.events.callRemote("sendFactionDataToCreateServer", user, pass, state); }); mp.keys.bind(0x1B, true, function() { if (openedConsole) { loginBrowser.destroy(); mp.gui.cursor.show(false, false); } }); mp.events.add('ShowFactionCreate', displayFactionDialoge); Which is included in the index.js which is in the same folder, then I got a folder with faction where this is .html is located: Then I got an assets folder where my css and js are and for this occasion we only need the main.js file which is in the folder of javascript: Main.js: mp.gui.chat.push("Main.js called"); function sendFactionData() { mp.gui.chat.push("SendFactionData - completed"); mp.trigger('SendFactionCreateData', $('#factionName').val(), $('#factionType').val()); } $('#confirmButton').click(function() => { mp.gui.chat.push("Login succedsadasdasssful"); mp.trigger('SendFactionCreateData', $('#factionName').val(), $('#factionType').val()); }); Now the issue is that the website will pop-up but when I fill in the information and press the create button it doens't do anything, I also tried to debug the main.js as you can see but that wasn't even executed so I am kinda wondering how this is possible. Thanks in advance! PS: I don't think it's needed because it isn't even being called to the main.js I believe but here is the server-side file factions.js: mp.events.add("sendFactionDataToCreateServer", (player, factionName, factionType, state) => { gm.mysql.handle.query('INSERT INTO `factions` SET factionName = ?, factionType = ?', [factionName, factionType], function(err, res){ if(!err){ console.log(` Faction ${factionName} has just been made.`); } else { console.log("\x1b[31m[ERROR] " + err) } }); });
-
<form action="index.php" method="POST"> <label for="username">Имя:</label><input type="text" name="name" class="placeholder" placeholder="Name_Surname" required> <label for="password">Пароль:</label><input type="password" name="password" class="placeholder" placeholder="Ваш пароль" required> <input type="submit" name="submit"value="Регистрация"> </form> Выше форма HTML А данный код, код запроса, просто файл index.php как выше action="index.php" можно создать свой файл, вместо index.php можно что либо другое, а можно ещё и HTML запрос кинуть вместе с Файлом Запроса <?php error_reporting(0); $connection = mysqli_connect('localhost', 'user', 'password', 'database') or die(mysqli_error($connection)); $db = $connection; if (isset($_POST['submit'])) { $name = $_POST['name']; $query = "SELECT playerName FROM accounts WHERE playerName='".$_POST['name']."'"; $result = mysqli_query($connection, $query); echo "Debug: ".mysqli_num_rows($result); if(mysqli_num_rows($result) > 0) { $info_reg = 'Данное имя уже зарегистрированно!'; } else { if (empty($_POST['name'])) { $info_reg = 'Введите имя'; } elseif (empty($_POST['password'])) { $info_reg = 'Введите пароль'; } elseif(empty($_POST['name']) == $name) { $info_reg = 'Уже зареган такое'; } else { $name = $_POST['name']; $pass = $_POST['password']; $query = "INSERT INTO `accounts` (playerName, playerPass) VALUES (')"; $result = mysqli_query($connection, $query) or die(mysqli_error($connection)); $info_reg = 'Успешная Регистрация!'; } } } $info_reg = isset($info_reg) ? $info_reg : NULL; echo $info_reg; ?>
-
[Module] AJCom (easy server/client communication) [v1.9.6]
RealMarcelo replied to ShrewdSpirit's topic in Resources
Hi ! I am new in this game, and I have some difficulties to use your module instead of the original way. For exemple, I need to do a registration form and I am stuck when I send a request from client side to know if player's username is already taken, or not. Client-sided code: function sendCredentials() { let name = $('#name').val(); ajcom.callServer('registerPlayer', name).then((ctx, result) => { /* In the future, that part will display error or success message to client */ console.log('Client: '+result); }); }; Server-sided code: function chefIfThatPlayerExists(name) { return DB.query("SELECT null FROM players WHERE name = ? LIMIT 1", name, function(error, result) { if(error) throw error; return result.length; }); }; // Shittery code, I checked all StackOverflow's problems about that subject and due to asynchrone queries, that will never work.... ajcom.register('registerPlayer', (hCtx, name) => { // The question is, how to do some MySQL queries inside ajcom.register eventHandler ? const exists = checkIfThatPlayerExists(name); console.log(exists); }); /* In wiki */ // server side ajcom.register('handler', (hCtx) => { if (hCtx.source === ajcom.ScriptType.Client) { // query player data const playerData = dbGetPlayerData(hCtx.client.name) return {money: playerData.money, perm: playerData.perm} } }) Also, I think that I am actually retarded, but I don't understand how I could use your module to simplify the process.. I tested all NodeJS standard resolutions about this, but I think that callbacks and promise will not be helpful in this case.. At every solution, your code needs to be inside the MySQL querying function... With the original way, that is pretty easy because I could call a function which returns result to client without any problem, but with Ajcom, problem is real as long as you must return the MySQL result outside it. Holy cow... If you could include an exemple with MySQL queries, that could actually help me a lot... thanks in advance. EDIT : Maybe should I use MySQL2 ( https://www.npmjs.com/package/mysql2#using-promise-wrapper ) ... ? Best regards, Marcelo -
Hi. When server started then running my script (and print good value(example: Retrieved 1 trashes)) but I connecting my server and object isn't seen. It's good if then execute my script when running the server. var cachedTrashes = []; function loadTrashes() { global.db.query("SELECT * FROM `trashes`", function(error, results, fields) { if(error) { console.log("error while retrieving trashes from mysql database! (" + error + ")"); } else { results.forEach(function(currElement) { let obj = mp.objects.new(mp.joaat("prop_bin_delpiero"), new mp.Vector3(parseFloat(currElement.x), parseFloat(currElement.y), parseFloat(currElement.z)), { rotation: 0.0, alpha: 255, dimension: parseInt(currElement.dim) }); obj.setVariable("inv:trash", true); cachedTrashes[parseInt(currElement.id)] = obj; }); console.log("Retrieved " + results.length + " trashes"); } }); } loadTrashes(); Please help me. Edit: If reconnected then I don't see again my server sided objects when I ran my script after server start.
-
This function is intended to simulate that the tires break when fired. getClosestVehicle() returns only one int, not the vehicle handle. Here is my working client-side script: mp.events.add('playerWeaponShot', (targetPosition) => { let nearestVehicle = mp.game.vehicle.getClosestVehicle(targetPosition.x, targetPosition.y, targetPosition.z, 2, 0, 70); if( nearestVehicle != 0 ) { // chance of damage if( Math.floor((Math.random() * 100) + 1) < 25 ) { for (var i = 0; i < 4; i++) { var DamagedWheel = Math.floor((Math.random() * 9)); mp.vehicles.atHandle(nearestVehicle).setTyreBurst(DamagedWheel, true, 1000); } } } }); But I think it's easier and safer to run these functions on the server side. Here is an example from my server: mp.events.add('vehicle_toggle_lock', (Player) => { var NearbyVehicles = []; mp.vehicles.forEachInRange(Player.position, 2.5, (NerbyVehicle) => { NearbyVehicles.push(NerbyVehicle); }); // sort the vehicles by range (0 is closest to the player) NearbyVehicles.sort(function(a, b){return b.dist(Player.position)-a.dist(Player.position)}); if( NearbyVehicles.length > 0 ) { if( NearbyVehicles[0].locked ) { NearbyVehicles[0].locked = false; Player.notify("You ~g~unlocked the vehicle."); // MySQL_Conn.query("UPDATE vehicles SET veh_locked='0' WHERE vehicle=?", [NearbyVehicles[0].data.id]); } else { NearbyVehicles[0].locked = true; Player.notify("You ~r~locked the vehicle."); // MySQL_Conn.query("UPDATE vehicles SET veh_locked='1' WHERE vehicle=?", [NearbyVehicles[0].data.id]); } } });
-
Hello! I want to share a mysql query function under one resource, I have got login.cs and mysql.cs and want to share this function to be able to use in login.cs public DataTable ExecuteQueryWithResult(string sql) { using (MySqlConnection conn = new MySqlConnection(connStr)) { try { MySqlCommand cmd = new MySqlCommand(sql, conn); conn.Open(); MySqlDataReader rdr = cmd.ExecuteReader(); DataTable results = new DataTable(); results.Load(rdr); rdr.Close(); return results; } catch (Exception ex) { NAPI.Util.ConsoleOutput("DATABASE: [ERROR] " + ex.ToString()); return null; } } } So the question is: How to use this function in other C# files under one resource? Is there any function like TriggerEvent, etc?
-
Good day to all! I recently started developing my server and decided to try doing all UI on React. Today I want to share how to set up a project for convenient work with this framework! I loaded the finished example on github: https://github.com/Mispon/rage-mp-react-ui There are also collected files in the archive server-files.rar for quick test. And now in order: First you need to initialize the project by running the command npm init Then install all the necessary packages. That is my packege.json file { "name": "rage-mp-react-ui", "version": "1.0.0", "description": "Example repo to explain how use react in rage mp servers", "main": "index.js", "scripts": { "start": "npm run dev", "dev": "set NODE_ENV=development && webpack", "prod": "set NODE_ENV=production && webpack" }, "repository": { "type": "git", "url": "git+https://github.com/Mispon/rage-mp-react-ui.git" }, "keywords": [ "rage-mp", "react", "rage", "mispon", "gta5", "gtav" ], "author": "Mispon", "license": "ISC", "bugs": { "url": "https://github.com/Mispon/rage-mp-react-ui/issues" }, "homepage": "https://github.com/Mispon/rage-mp-react-ui#readme", "devDependencies": { "babel-core": "^6.26.3", "babel-loader": "^7.1.5", "babel-preset-es2015": "^6.24.1", "babel-preset-react": "^6.24.1", "css-loader": "^1.0.0", "node-sass": "^4.9.3", "sass-loader": "^7.1.0", "style-loader": "^0.23.0", "webpack": "^4.20.2", "webpack-cli": "^3.1.2" }, "dependencies": { "react": "^16.5.2", "react-dom": "^16.5.2" } } You can do it by command npm i packetname --save (or --save-dev if packet will use only in developing, like babel-core and etc). Next you need to create webpack.config.js and paste the following settings into it: const webpack = require('webpack') const path = require('path') let NODE_ENV = 'production' if (process.env.NODE_ENV) { NODE_ENV = process.env.NODE_ENV.replace(/^\s+|\s+$/g, "") } module.exports = { entry: { index: './index.js', app: './ui/app/app.js' }, output: { path: path.resolve(__dirname, 'build'), filename: '[name].js' }, watch: NODE_ENV == 'development', module: { rules: [{ test: /\.js$/, exclude: [/node_modules/], loader: 'babel-loader', query: { presets: ['react', 'es2015'] } }, { test: /\.scss$/, use: ["style-loader", "css-loader", "sass-loader"] } ] }, resolve: { extensions: ['.js', '.json'] }, optimization: { minimize: true }, mode: NODE_ENV, plugins: [ new webpack.EnvironmentPlugin('NODE_ENV') ] } I will not go into details, there is documentation for this. In short, the webpack will collect all the files of our application into one (or several) ready-made files (and styles too!). Then create clients index.js file, a separate folder for the UI with single index.html, app.js, bridge.js and some style file. In my case I use .scss. After you got something like that: In index.js add simple code for test how events works: let browser mp.events.add('guiReady', () => { browser = mp.browsers.new('package://ui/index.html') }) // Handle event from server and send data to react app mp.events.add('onMessageFromServer', (value) => { browser.execute(`trigger('onMessage', '${value}')`) }) // Handle event from react app mp.events.add('showUrl', (url) => { mp.gui.chat.push(url) }) // F12 - trigger cursor mp.keys.bind(0x7B, true, () => { let state = !mp.gui.cursor.visible mp.gui.cursor.show(state, state) }) In app.js we'll add our example react component and render it in index.html: import '../styles/app.scss' import React from 'react' import ReactDOM from 'react-dom' class App extends React.Component { constructor(props) { super(props) this.state = { time: new Date(), message: 'default message' } } componentDidMount() { EventManager.addHandler('onMessage', this.onMessage.bind(this)) this.timerId = setInterval(() => { this.setState({time: new Date()}) }, 1000) } componentWillUnmount() { clearInterval(this.timerId) EventManager.removeHandler('onMessage', this.onMessage) } onMessage(value) { this.setState({message: value}) } // send current url to client click() { let currentUrl = window.location.pathname mp.trigger('showUrl', currentUrl) } render() { return( <div className="app"> <h1>Make UI on React!</h1> <p className="current-time">{this.state.time.toLocaleTimeString()}</p> <p className="message">{this.state.message}</p> <button className="send-button" onClick={this.click}>Send</button> </div> ) } } ReactDOM.render(<App />, document.getElementById('root')) Here everything is as in normal work with the react. At the very beginning we connect our styles. You can define them to your taste. Next, create the component, define the default state, write the HTML code that will be rendered in the browser, and add the necessary handlers in the component. But there is one very important point! In the componentDidMount method, using the EventManager which is global space, we subscribe to the event that will be passed from the client to our react-application. At its core, EventManager is a bridge between client multiplayer code and our UI. Let's define EventManager in our bridge.js: // Global variable for describe on events from react components var EventManager = { events: {}, addHandler: function(eventName, handler) { if (eventName in this.events) { this.events[eventName].push(handler); } else { this.events[eventName] = [handler]; } }, removeHandler: function(eventName, handler) { if (eventName in this.events) { var index = this.events[eventName].indexOf(handler); this.events[eventName].splice(index, 1); } } } // Handle events from client function trigger(eventName, args) { var handlers = EventManager.events[eventName]; handlers.forEach(handler => handler(JSON.parse(args))); } The trigger function serves as the only point of access to our UI from the client and delegates execution to the accessible handler by the name of the event. That is, in any component we can create a handler, subscribe to an event interesting to us and update its state depending on what happens in the game. In client code we will only use browser.execute(`trigger('eventName')`). In addition as simple as possible index.html and my app.scss: <html> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- Don't forget to change paths after copy in server packages --> <script src="app/bridge.js" defer></script> <script src="../build/app.js" defer></script> </head> <body> <div id="root"></div> </body> </html> .app { h1 { text-align: center; font-weight: bold; padding-top: 2vh; } .message { text-align: center; font-size: 2vw; padding-top: 2vh; } .current-time { display: block; position: absolute; right: 1vw; bottom: 0; } .send-button { display: block; width: 100px; height: 50px; margin: 15% auto; outline: none; } position: relative; width: 30%; height: 40vh; margin: 20vh auto; border-radius: 10px; box-shadow: 1px 1px 2px black; background-color: black; color: white; } Now you can run the npm start or npm run dev in the root directory to build the project. Check full example usage on my github, link above. Hope it's help for someone. Be good in developing! Mispon (discord: Mispon#8498)
-
It started since i added lo4js. i think he writes logs in a file. Its okay. Just warn for long mysql query. I use innoDB with utf8
-
Привет! Вот у меня что получилось, паспорт не открывается. Команда на сервере: mp.events.addCommand("pass", (player, fname, surname, birthday)=> { gm.mysql.handle.query('SELECT fname, surname, birthday FROM `accounts` WHERE `username` = ?', [fname, surname, birthday, player.name]); player.call("showPassport", [fname, surname, birthday]); }); Вот то что в клиенте: mp.events.add("showPassport", (fname, surname, birthday)=> { let passportBrowser = mp.browsers.new('package://passport/index.html'); mp.gui.cursor.show(true, true); mp.events.add('browserDomReady', (browser) => { if(browser === passportBrowser) { browser.execute(`updateData(${fname},${surname}, ${birthday} )`) } }); }); Не открывается паспорт и ничего не происходит.
-
Error: async hook stack has become corrupted (actual: 10, expected: 11) setInterval(function() { mp.players.forEach(function(player){ mp.trigger('playerAutoSave', player); }); }, 8000); mp.events.add("playerAutoSave", (player) => { player.loggedInAs = ""; gm.mysql.handle.query("UPDATE `account` SET money = ?, posX = ?, posY = ?, posZ = ? WHERE `username` = ?", [player.money, player.position.x, player.position.y, player.position.z, player.name], function(err,res){ if(!err){ console.log(`[Auto Save] Es wurden alle Accounts gespeichert.`) } else ( console.log("ERROR: " + err) ) }); }); Some fixxes avaible?
-
If you're looking to store variables like that, all you'd have to do is send a query to the database. I don't know much C# so I can't really type it out. Check out the auth.js file for examples of sending queries. The loadAccount function inside auth.js shows how data from the database is loaded onto the player as well.
- 20 comments
-
I updated the query, to make it work on MySQL 8.0 also.
-
Подскажите, в чем может быть ошибка ? events.js:4638: Uncaught Error: Connection lost: The server closed the connection. { Error: Cannot enqueue Query after fatal error. at Protocol._validateEnqueue (C:\Users\akexd\Desktop\RageMp\server\node_modules\mysql\lib\protocol\Protocol.js:201:16) at Protocol._enqueue (C:\Users\akexd\Desktop\RageMp\server\node_modules\mysql\lib\protocol\Protocol.js:139:13) at Connection.query (C:\Users\akexd\Desktop\RageMp\server\node_modules\mysql\lib\Connection.js:208:25) at register (C:\Users\akexd\Desktop\RageMp\server\packages\keker\cmds\registration.js:29:23) at playerCommand (C:\Users\akexd\Desktop\RageMp\server\packages\keker\events\OnPlayerCommand.js:21:4) code: 'PROTOCOL_ENQUEUE_AFTER_FATAL_ERROR', fatal: false } База есть. Все нужные таблицы создались.
-
Мне кажется, что в исходной базе данных есть другие записи, те, которые вы пробовали? Static analysis: 2 errors were found during analysis. Unexpected beginning of statement. (near "phpMyAdmin" at position 0) Unrecognized statement type. (near "SQL" at position 11) SQL query: phpMyAdmin SQL Dump -- version 4.5.4.1deb2ubuntu2 -- http://www.phpmyadmin.net -- -- Host: localhost -- Generation Time: Dec 26, 2017 at 11:07 PM -- Server version: 5.7.20-0ubuntu0.16.04.1 -- PHP Version: 7.0.22-0ubuntu0.16.04.1 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO" MySQL said: #1064 - You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'phpMyAdmin SQL Dump -- version 4.5.4.1deb2ubuntu2 -- http://www.phpmyadmin.net -' at line 1 Who's better at mysql? Do you have any ideas? I use xampp.
-
Yes, have found the cause, but do not know what's wrong with it. function savePlayerAccount(player) { const position = misc.convertOBJToJSON(player.position, player.heading, 0.1); misc.query(`UPDATE users SET position = '${position}', dim = '${player.dimension}', lastlogindate = '${new Date()}' WHERE username = '${player.name}'`); misc.log.debug(`${player.name} gespeichert`); }
