Demo:
<?php
function get_connection() {
$con = new mysqli('localhost', 'root', '', 'Test');
if(mysqli_connect_errno()) {
die(mysqli_connect_error());
}
return $con;
}
function insert($con, $stmt, $un, $pw) {
$stmt->bind_param('ss', $un, $pw);
$stmt->execute() or die(mysqli_error($con));
}
function setup() {
$con = get_connection();
$con->query('CREATE TABLE unpw (un VARCHAR(32), pw VARCHAR(256), PRIMARY KEY(un))') or die(mysqli_error($con));
$stmt = $con->prepare('INSERT INTO unpw VALUES(?,?)') or die(mysqli_error($con));
insert($con, $stmt, 'A', 'Not updated');
insert($con, $stmt, 'B', 'Not updated');
insert($con, $stmt, 'C', 'Not updated');
insert($con, $stmt, 'D', 'Updated');
$stmt->close();
$con->close();
}
function dump() {
$con = get_connection();
$rs = $con->query('SELECT un,pw FROM unpw') or die(mysqli_error($con));
while($row = $rs->fetch_array(MYSQLI_ASSOC)) {
$un = $row['un'];
$pw = $row['pw'];
echo "$un $pw\r\n";
}
$con->close();
}
function teardown() {
$con = get_connection();
$con->query('DROP TABLE unpw') or die(mysqli_error($con));
$con->close();
}
function superhash($pw) {
return 'Updated';
}
function update() {
$selcon = get_connection();
$updcon = get_connection();
$selstmt = $selcon->prepare('SELECT un,pw FROM unpw WHERE pw = ?') or die(mysqli_error($selcon));
$updstmt = $updcon->prepare('UPDATE unpw SET pw = ? WHERE un = ?') or die(mysqli_error($updcon));
$targetpw = 'Not updated';
$selstmt->bind_param('s', $targetpw);
$selstmt->execute() or die(mysqli_error($selcon));
$rs = $selstmt->get_result();
while($row = $rs->fetch_array(MYSQLI_ASSOC)) {
$un = $row['un'];
$pw = $row['pw'];
$newpw = superhash($pw);
$updstmt->bind_param('ss', $newpw, $un);
$updstmt->execute() or die(mysqli_error($updcon));
}
$updstmt->close();
$selstmt->close();
$updcon->close();
$selcon->close();
}
setup();
dump();
update();
dump();
teardown();
?>