Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

I tried search google "mysql column value" and "mysql row value" and couldn't quite find what I am looking for.

What's the easiest or most efficient way to retrieve a single column from a table? I am used to pulling back numerous columns at a time using bind_columns. I could use this but that's the wrong tool for the job.

Any help or link to a tutorial or node somewhere would be very much helpful.

Replies are listed 'Best First'.
Re: how do get value of mysql column
by davidrw (Prior) on Nov 30, 2005 at 19:05 UTC
Re: how do get value of mysql column
by jZed (Prior) on Nov 30, 2005 at 20:27 UTC
    To get the values of a single column for all rows matching a query do:
    my $aryref = $dbh->selectcol_arrayref( $sql,{},@binds );
    
    To get the value of a single column for a single row matching a query do:
    my($value) = $dbh->selectrow_array( $sql,{},@binds );
    
    In both cases, the SQL query should specifiy only a single column in the SELEC list, e.g. SELECT foo FROM ...
Re: how do get value of mysql column
by Koolstylez (Scribe) on Nov 30, 2005 at 18:58 UTC
    The following SQL statement should do the trick:

    SELECT <column_name> FROM <table_name>

    If you only want the column value for certain records, filter it like so:

    SELECT <column_name> FROM <table_name> WHERE <clause>

    As for a tutorial, I would suggest finding a good SQL tutorial on Google, there are tons of them.

    Hope this helps...
      using dbi:
      $sth = $dbh->prepare("SELECT column FROM table"); $sth->execute; $column_value = $sth->fetchrow;
Re: how do get value of mysql column
by duckyd (Hermit) on Nov 30, 2005 at 19:42 UTC
    depending on the number of rows you expect to be returned, and what you're doing with them (among other things), you may find the fetchall_* or selectall_* DBI methods are useful.