Database Quick Start: Example Code
The following page contains example code showing how the database library is used. For complete details please read the individual pages describing each method.
Initializing the Database Library
The following code loads and initializes the database library based on your configuration settings:
get rigLoadDatabase()
Once loaded the library is ready to be used as described below.
Note: If all your pages require database access you can connect automatically. See the connecting page for details.
Standard Query With Multiple Results
put rigDbQuery("SELECT name, title, email FROM myTable") into tQuery
repeat with i = 1 to tQuery["numrows"]
put rigDbRow(i) into tRowData
put tRowData["title"] & comma after tResultData
put tRowData["name"] & comma after tResultData
put tRowData["email"] & return after tResultData
end repeat
The above rigDbQuery() function returns an array.
Testing for Results
If you run queries that might not produce a result, you are encouraged to test for a result first:
put rigDbQuery("YOUR QUERY") into tQuery
# CHECK IF THE QUERY RESULT HAS DATA
if tQuery["numrows"] > 0 then
repeat with i = 1 to tQuery["numrows"]
put rigDbRow(i) into tRowData
put tRowData["title"] & comma after tResultData
put tRowData["name"] & comma after tResultData
put tRowData["body"] & return after tResultData
end repeat
end if
Standard Query With Single Result
get rigDbQuery("SELECT name FROM myTable LIMIT 1")
put rigDbRow(1) into tRow
put tRow["name"] into tName
Standard Insert
put "INSERT INTO mytable (title, name) VALUES (" & rigDbEscape(tTitle) & ", " & rigDbEscape(tName) & ")" into tSQL
get rigDbQuery(tSQL)
put rigDbAffectedRows() into tAffectedRows
The function rigDbAffectedRows() returns an integer or a boolean.
Active Record Query
The Active Record Pattern gives you a simplified means of retrieving data:
put rigDbGet("tableName") into tQuery
repeat with i = 1 to tQuery["numrows"]
put rigDbRow(i) into tRowData
put tRowData["title"] & comma after tTitles
end repeat
The above rigDbGet() function retrieves all the results from the supplied table. The Active Record library contains a full compliment of handlers for working with data.
Active Record Insert
put tTitle into tData["title"]
put tName into tData["name"]
put tDate into tData["date"]
get rigDbInsert("mytable", tData)
-- Produces: "INSERT INTO mytable (title, name, date) VALUES ('" & tTitle & "', '" & tName & "', '" & tData & "')"