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

$sth = $dbh->prepare("SELECT `username`,`password`,`group` FROM `user +s`"); $sth->execute;
thats not dont yet I need it to only choose the ones that where group is equal to admin

Replies are listed 'Best First'.
Re: MySQL
by stajich (Chaplain) on Jul 18, 2002 at 21:38 UTC
    Add WHERE group = 'admin' See many helpful online SQL tutorials for more information. You don't need the extra ' in your stmt.
    $sth = $dbh->prepare("SELECT username,password,group FROM users WHERE group = 'admin'"); $sth->execute(); while( my ($user,$pass,$group) = $sth->fetchrow_array ) { print "$user,$pass,$group\n"; }
    UpdateAh hah, you are using 'group' which is a reserved word for most RDBMs. Are you really sure that is what your table structure looks like?

      This is an excellent candidate for abstraction:

      sub get_group { my ($dbh, $group) = @_; my $sth = $dbh->prepare( "SELECT username, password, group FROM users WHERE group = ?"); $sth->execute($group) or warn "Can't select on group: $DBI::errstr\n"; my @users = (); while( my $user = $sth->fetchrow_hashref()) { push @users, $user; } return @users; }

      --
      The hell with paco, vote for Erudil!
      :wq

Re: MySQL
by screamingeagle (Curate) on Jul 18, 2002 at 22:50 UTC
    you're enclosing the column names and the table names in single quotes. try removing them ...and add the where clause like stajich suggested :
    $sth = $dbh->prepare("SELECT username,password,group FROM users where +group = 'Admin'"); $sth->execute;
    In SQL Server, the check is not case-sensitive, however , if you're using oracle, you might want to write the SQL Stmt like this :
    SELECT username,password,group FROM users where upper(group) = upper('admin')
    hth...
      screamingeagle wrote:

      In SQL Server, the check is not case-sensitive, however , if you're using oracle, you might want to write the SQL Stmt like this :

      SELECT username,password,group FROM users where upper(group) = upper('admin')
      The problem with this is that unless the database engine is very advanced, this will table scan instead of using an index. The reason is that it needs to run a function on one of your columns, and the optimizer has no idea what the result of that function call will be before hand. So, it needs to calculate it for every row when you do your query.

      You are in luck, however, in that there are alternative solutions to the problem. One is to create a rule on the column that only allows certain known values. The second is to have the upper in your insert statement, thus canonicalizing the values in the column. I'm sure there are more, but this should get you started.

      thor