How to create a new column containing id column hash

I have a table containing 1 column id. Now I want to create a new column for my table. Therefore, I want the data of the new column to be hashed id. something like that:

// my table
+------+
|  id  |
+------+
|  1   |
|  2   |
|  3   |
+------+

// I want this table
+------+------------+
|  id  |   hashed   |
+------+------------+
|  1   |  00320032  |
|  2   |  00330033  |
|  3   |  00340034  |
+------+------------+

It should be noted that the column is hashedbased:

hash('adler32', '1'); // output: 00320032

hash('adler32', '2'); // output: 00330033

hash('adler32', '3'); // output: 00340034

Now, is it possible to do this?

+4
source share
1 answer

Among other possible approaches, you can first get all ids, calculate the hashed values ​​for each of them, and again insert the available date back into the table (and avoid duplicates :)

The following is interesting (error checking is not performed :)

<?php
// Adding the column named 'hashed'
$mysqli->query('ALTER TABLE your_table ADD COLUMN (`hashed` INT);');

// Retrieving all the 'id's
$result = $mysqli->query('SELECT id FROM your_table;');
$IDs = $result->fetch_all(MYSQLI_ASSOC);
$result->close();

// Assembling the values for a bulk INSERT statement
$values = array();
foreach($IDs as $row) {
    $ID = $row['id'];
    $hashed = hash('adler32', $ID);
    $values[] = "($ID, $hashed)";
}
$values = implode(',', $values);

// Delete to avoid duplicates
$mysqli->query("DELETE FROM your_table;");

// Insert the 'id and their respective hashed values
$mysqli->query("INSERT INTO your_table (id, hashed) VALUES $values;");
+1
source

All Articles