On Thursday 07 June 2001 16:15, Pete Emerson wrote:
> I have some questions about the following code snippet (using DBI to
> connect to MySQL):
>
> 1. $prep_query="SELECT school_name,path from student_data where
> student_id=$student_id";
> 2. $query=$dbh->prepare($prep_query);
> 3. $query->execute;
> 4. $temp=$query->fetchall_arrayref();
> 5. foreach my $row (@$temp) {
> 6. ($school,$path)=@$row;
> 7. # Do stuff with each $school, $path here
> 8. }
>
> 1. Is there a nice way to combine lines 1-3 or 1-4 into one nice easy
> statement?
Newer versions of DBI should contain selectall_arrayref function which
combines lines 1-4.
> 2. Is line 4 fetchall_arrayref returning a pointer $temp which points to
> the beginning of an array?
It's not a pointer, it's a reference (there are no C pointers in Perl; you
can think about reference as "smart pointer"). You can, for example, refer to
single rows by $temp->[$row_number] and to cells by
$temp->[$row_number]->[$col_number];
> 3. And then I access the elements of the array by using @$temp in line
> 5?
yes.
> 4. Is line five treating $row as a pointer to an array?
if you replace 'pointer' with 'reference'', answer is yes :)
> 5. ... in order to break it up into the individual elements on line 6
> with @$row?
yes.
> 6. Any easy ways to compact/clarify this code would be terrific, I do
> this sort of thing a lot. I know that I can just make a subroutine out
> of it and do some variable passing, but I am also looking for ways to
> compact the code itself as well as really understand what is going on.
>
> If I know I'm returning just one result, I use this:
>
> $prep_query="SELECT school_name, path from student_data where
> student_id=$student_id";
> $query=$dbh->prepare($prep_query);
> $query->execute;
> ($school,$path)=$query->fetchrow_array();
>
> Any easier ways to compact this one would also be terrific.
>
look at selectrow_array function (if you have recent version of DBI).
> Thanks in advance. Perl rocks.
> Pete
--
Ondrej Par
Internet Securities
Software Engineer
e-mail: [EMAIL PROTECTED]
Phone: +420 2 222 543 45 ext. 112