MySQL callback returning null? Need help

When I call getWeight and it calls getPlayerData it returns null, but “PrintTable(q[1])” prints a table of the data but when I actually try to return that data back to getWeight its null. I’m so confused.

function Inventory:getWeight(ply)

	return SQL:getPlayerData(ply,"Weight")


function SQL:getPlayerData(ply,field)
		local fetchQuery = db:query("SELECT * FROM Players WHERE SteamID= '" .. ply:SteamID64() .. "'")

		function fetchQuery:onSuccess(q)
			if not verifyPlayer(fetchQuery) then
				print("Does Not Exist")
					return q[1]

		function fetchQuery:onError (q,e)
			return nil
		function fetchQuery:OnData(q,data)


You can’t return the data in a callback. It isn’t possible. You’ll have to do whatever you need with the data in the callback itself.

Can you offer a simple example?

You’re going to need to have getWeight have a callback and run getWeight’s callback in the query’s OnData function. Or you can load the weight once somewhere and store it.

Is getWeight being ran clientside?

Not sure if this is the case, but AFAIK SQL queries can only be ran/returned serverside if not networked.

You’re returning to whatever called the onSuccess function, considering that function isn’t called within getPlayerData function, there’s no way for it to return.

Usually when handling database stuff like this you have 2 options. First is you store all player data when they join, that way you can access it whenever. Second is you use callbacks, i.e. you pass a function to the getPlayerData function which then will get called whenever the query finishes.


function SQL:getPlayerData(ply, field, callback)
  -- query code

  function fetchQuery:onSuccess(q)

  -- other code

If this was being called client side it’d error, that is unless the person had a cl version of the module installed.

So would the callback be a function? I’m not sure I understand how I could use that to bring the return value back to the getWeight function

Yes, it would be a function. No, you cannot return the value back to the getWeight function. Stop trying to returning anything here, it’s not possible. You can store the data on the player in the callback but you can’t have Inventory:getWeight return it.


Well the point here is, is that you “can’t”. Only way you’d be able to do that would be if you stored the value when the player joined, and updated it as it changed.

The reason I put “can’t” above is because most mysql modules allow you to force the lua state to wait until the query finishe. The reason you don’t want to do this (in most cases) is because it’ll cause the server to freeze for however long your query took (usually .04 - .4 depending).