Q:

SQL Server PDO UPDATE loop error

I'm trying to write a script to hash some temporary passwords. For now the temporary password and the hashed version are stored in the same table. As soon as I get them hashed, I'm going to drop the unhashed column. The problem is: My script is setting all hashed passwords to match the last record in the table.
$conn = new PDO("sqlsrv:Server=localhost;Database=database", "sqlUser", "password");
$result = $conn->prepare("SELECT tempPassword FROM employeeTable");
$result->execute();
$sql = "UPDATE employeeTable SET hashTempPass = :tempPass ";

while($data = $result->fetch(PDO::FETCH_ASSOC)) 
{
    $tempPass = $data['tempPassword'];  
    $q = $conn->prepare($sql);
    $q->bindValue(':tempPass', $tempPass);  
    $q->execute();
}

Results are as such
user1    unhashPass1    hashpass3
user2    unhashPass2    hashpass3
user3    unhashpass3    hashpass3

Whereas what I need is
user1    unhashPass1    hashPass1
user2    unhashPass2    hashPass2
user3    unhashpass3    hashpass3

I hope this question is clear enough. Thank you.
Edit: Since I was struggling with this, I'm not yet hashing the passwords until I get this code working.

A:

You are close but you need to change the query:
SELECT user, tempPassword FROM employeeTable

and
UPDATE employeeTable SET hashTempPass = :tempPass WHERE user = :user

this will allow you to grab both hash and temp password.
You can then update the table based on the temp password:
$conn = new PDO("sqlsrv:Server=localhost;Database=database", "sqlUser", "password");
$result = $conn->prepare("SELECT hash, tempPassword FROM employeeTable");
$result->execute();

//prepare it only once (no need to send query to server at each iteration
$sql = "UPDATE employeeTable SET hashTempPass = :tempPass WHERE user = :user";
$q = $conn->prepare($sql);

while($data = $result->fetch(PDO::FETCH_ASSOC)) 
{
    $tempPass = $data['tempPassword'];  
    $user = $data['user']; 

    $q->bindValue(':tempPass', $tempPass);  
    $q->bindValue(':user', $user);  

    $q->execute();
}

Note

I called the field user but you will need to adjust that column
field to match your table of course.
UPDATE without WHERE clause can lead you to the biggest mistake a database admin can do.

