I'm having trouble writing a function that will output an array of records. What I am attempting to do is call a function that gets all the records in a table and will create a multi-dimensional array that I can use in the page that calls the function.
Can you tell me what I'm doing wrong?
function get_admins
set rs = Server.CreateObject("ADODB.recordset")
rs.cursorType = 3
getsql = "select * from users order by name asc"
rs.Open getsql, conn
total = rs.RecordCount
ra = array
c = 0
if total < 1 then
o = "There are no admins yet."
else
do until rs.EOF
id = rs.Fields("id").value
username = rs.Fields("username").value
adminname = rs.Fields("name").value
email = rs.Fields("email").value
Redim Preserve ra(c,4) '<-- This is the line the error doesn't like
ra(c,0) = id
ra(c,1) = username
ra(c,2) = adminname
ra(c,3) = email
c = c + 1
rs.MoveNext
loop
end if
rs.close
get_admins = ra
end function
This is the error I get:
Microsoft VBScript runtime error '800a0009'
Subscript out of range
Function call on the page looks like this:
<pre><%
dim seeme
set seeme = get_admins
%></pre>
Here are some similar questions I found:
Classic ASP 3.0 Create Array from a Recordset – Helped a lot, but not quite there.
Redim Preserve gives 'subscript out of range' – This one just straight confused me.
Best Answer
ReDim Preserve
can only change the size of the last dimension in multidimensional arrays, so it's not really useful in your situation. What you can use is an array of arrays, though:That will allow you to access the elements of the nested arrays like this:
The above will print the 2nd value (index 1) from the 4th nested array (index 3).
As for returning the array, you cannot use the
Set
keyword in the assignment:That's because that keyword is reserved for object assignments and arrays aren't objects. Change that line to this: