If you are going to do something like this, I would write a separate PHP file that reads & writes to the file in question.
Embedding php in a .htpasswd file won't work, but writing a modifyHtpasswd.php file and running it from the command line will work (pending file permissions).
Of course, you'll need to make sure your usernames and passwords are encoded correctly in your database for this to work.
<?php
mysql_connect("yourserver","uname","pass");
mysql_select_db("db");
$userString = "";
$sql = "select username,pw from users";
$result = mysql_query($sql);
while($row = mysql_fetch_array($result)){
$userString .= $row['username'] . ":" . $row['pw'] . "\n";
}
$fd = fopen("/path/to/.htpasswd","w+");
fwrite($fd,$userString);
fclose($fd);
?>