in reply to Reading data from mySQL into hashes and manipulation of hashes
Suggestion for your first question: You don't seem to be using all the rows that are returned from your query, so first, rather than selecting '*' you should select only the columns you want by name (since I don't know your column names this is only an example)
SELECT column1,column2,column3 FROM table WHERE column4=?";
Second suggestion has to do with the '?' on the end of my example. This is called a place holder and you should always use them. Why? Because DBI will then escape any bad characters for you. Also using this method your query will be cached and you can call it will lots of different parameters more than once without rebuilding the query, saving on coding time and speed for your program. (they are great in loops). You add the parameters by passing what you want in that question mark with the execute statement.
A 'gotcha' of placeholders however is that you can only use them to represent values, you can't use them to represent table or column names or other pieces of a statement. (in other words something like this:
would not work).SELECT ? FROM ? WHERE ?=?
Finally, instead of using $sth->fetchrow_array() use $sth->fetchrow_hashref(). This will return a reference to the hash you're looking for. The keys to this hash are your column names. So your final code would look something like this:
my $query = "SELECT column1,column2,column3 FROM table WHERE column4=? +"; my $sth = $dbh->prepare($query); $sth->execute($value_for_placeholder) or die $sth->errstr(); my $hash_ref = $sth->fetchrow_hashref(); # if its easier for you, you can dereference that hash_ref: my %hash = %$hash_ref;
Voila! and there you have it. I hope that helps!
Chris
Lobster Aliens Are attacking the world!
|
|---|