1

I'm trying to add some UUID's to my users table. I'm having a foreach loop which should generate a unique UUID for every user in my db. The problem is that every user is getting the same UUID in the db, but when I add a "echo" i see that it generates a separate UUID for every user, but that is not reflected in the db. Is PDO doing some sort of caching, as it doesn't care about that the $uuid variable is changing?

function getAllIds($db) {
$stmt = $db->query("SELECT id from users;");
$array = $stmt->fetchAll();
return $array;
}

foreach (getAllIds($db) as $ids) {
$uuid = uuid();
print "$uuid\n";
$stmt = $db->prepare("update users set user_uuid = ?");
$stmt->execute(array($uuid));
}

2 Answers 2

1

Try adding a user id on the where clause:

function getAllIds($db) {
    $stmt = $db->query("SELECT id from users;");
    $array = $stmt->fetchAll(PDO::FETCH_ASSOC);
    return $array;
}

$stmt = $db->prepare("UPDATE users SET user_uuid = :uuid WHERE id = :id");
$ids = getAllIds($db);
foreach ($ids as $k => $id) {
    $uuid = uuid();
    $stmt->execute(array(':uuid' => $uuid, ':id' => $id['id']));
}
Sign up to request clarification or add additional context in comments.

3 Comments

Why $ids[$k] instead of $id? Isn't that the point of using foreach rather than for?
@ghost I have tried your solution, but I am getting a "Array to string conversion..." error
@TheG oh i forgot, this is a multi dimensional, check my revision
1

The problem is that you are always updating the id of all entries inside your foreach loop. So when the fooreach loop has finished, all entries in the database will have the last chosen uuid as id.

Instead you must make sure to only modify a single database entry with each run of the loop. You can do that by specifying the entries in inside a where clause to the update statement.

$query = $db->prepare("UPDATE users SET user_uuid=:uuid WHERE id=:id");
foreach (getAllIds($db) as $entry)
  $query->execute(array(':uuid'=>uuid(), ':id'=>$entry['id']));

A side aspect: you should prepare that update statement only once: before the foreach loop. No need to repeat that step with every run.

1 Comment

You are absolutely right about preparing the statement before the loop.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.