accessing query responses with lua-resty-mysql

399 views
Skip to first unread message

david...@gmail.com

unread,
Nov 2, 2015, 9:16:06 AM11/2/15
to openresty-en
The lua-resty-mysql documentation uses cjson.encode() to demonstrate how to access a mysql select query response. I want to access the "id" column from my response but get error messages. For example, when I cjson.encode() the response to ngx.log() I get (as expected):
[{"weight":2453,"id":"84200"}]

but when I try to access the "id" column from the results table via the following code:

  local Query = "SELECT id FROM docs WHERE MATCH(" .. Quoted_Email .. ")"
  local Res, Err, Errno, Sqlstate = db:query(Query, 10)
  ngx.log(ngx.ERR, "DocID: ", Res["id"])

I get:
  DocID: nil

When I try looping through the table with:
  for key,value in pairs(Res) do ngx.log(ngx.ERR, key,value) end

I get:
  bad argument #2 to 'log' (string, number, boolean, or nil expected, got table)
  stack traceback: ...

I verified that Res is a table, how can I access the id column without json encoding the response?

thanks!

- D

david...@gmail.com

unread,
Nov 2, 2015, 3:46:11 PM11/2/15
to openresty-en
On Monday, November 2, 2015 at 4:16:06 PM UTC+2, david...@gmail.com wrote:

I verified that Res is a table, how can I access the id column without json encoding the response?


Problem solved via:

  local counter = 1
  while counter <= #res do
    ngx.log(ngx.ERR, "DocID: ", Res[counter]["id"])
    counter = counter + 1
  end

Chris Tanner

unread,
Nov 3, 2015, 6:05:05 AM11/3/15
to openresty-en
With your first example, it should work if you change it to:

 for key,value in pairs(Res) do ngx.log(ngx.ERR, key,value.id) end

'value' in your first example is actually a table representing one of the rows returned by your mysql query, with the column name as the keys.
Since lua doesn't know how you want it to print a table, it warns you that you provided a table and not a string/number/etc; the example in lua-resty-mysql is just using cjson as an easy way to print out a table in a readable way.

Hope that helped!

Cheers,
Chris
Reply all
Reply to author
Forward
0 new messages