code:
$dbh = mysql_connect("localhost", "user", "pass");
if(!$dbh) {
echo "Could not connect to database: " . mysql_error();
exit;
} // end if
// $dbh == our database handle
mysql_select_db("mydb", $dbh);
// Make a query...
$result = mysql_query("select * from table where col_1 = 3", $dbh);
if(!$result) {
echo "Could not perform query: " . mysql_error();
exit;
} // end if
// ... then pull the info out of the DB, line by line, into an array
$results = Array();
$i = 0;
while($resline = mysql_fetch_array($result)) {
$results[$i] = $resline;
$i++;
} // end while
// We now have our results array. Loop through it and do stuff.
// (using the $i index from above as our array length rather than
// sizeof($results), just because I'm weird)
for($j = 0; $j < $i; $j++) {
$returned_val = do_something_smart_with_row($results[$j]);
$sql = "update table set col_2 = '$returned_val' "
. where col_1 = '" . $results[$j]["col_1"] . "'";
$thisres = mysql_query($sql);
if(!$thisres) {
echo "Could not perform query: " . mysql_error();
exit;
} // end if
} // end for
mysql_close($dbh);
code:
use DBI;
our $dbh = DBI->connect("DBD:mysql:mydb", "user", "pass")
or die "Could not connect to database: $DBI::errstr";
# $dbh is the database handle
# Query from the DB and get all the results in a single hash
my $results = $dbh->selectall_hashref("select * from table where col_1 = 3")
or die "Could not perform query: $DBI::errstr";
# Loop through the hash and do stuff
foreach my $key (keys %{$results}) {
my $returned_val = &do_something_smart_with_row($results->{$key});
my $sql = "update table set col_2 = '?' where col_1 = '?'"
# the ?s get replaced with the 2nd+ arguments in the
# do() method of the database handle...
$dbh->do($sql, undef, $returned_val, $key)
or die "Could not perform query: $DBI::errstr";
} // end foreach
$dbh->disconnect();