First, the sha512
function is not a random function. If you pass it once or thousands of times the same string, it will always return the same hash. If you run the following command in your console, you will verify:
for i in $(seq 1 20); do php -r "echo hash('sha512', 'hola') . PHP_EOL;"; done
It is important to understand that the functions sha *, md5, etc are asymmetric algorithms: You can not recover the original value from the generated hash.
It is always advisable to use prepared statements
, so that your parameters can be escaped when you select or insert in the BD (in this case using PDO).
Specifically, and assuming that you use PDO, you should do something like the following:
$conn = new PDO(...);
$stm = $conn->prepare("INSERT INTO nombre_tabla VALUES(null, '', '', ?, '', ''");
$hash = hash('<algoritmo escogido>', $string);
$stm->execute(array($hash));
and then to select:
$stm = $conn->prepare($query = "SELECT id_tabla FROM nombre_tabla WHERE string = ?");
$hash = hash('<algoritmo escogido>', $string);
$stm->execute(array($hash));
In addition, it is important to mention that the function hash
returns a string in hexadecimal format, so it is not necessary to apply any further extra transformation ( base64
for example).
It occurs to me that the problem you may have is that your field in the database has a shorter length than that generated by the hashing function. Note that sha512 generates a 128-character long hash:
$ php -r "echo strlen(hash('sha512', 'hola'));" # correr en una consola
so it is cut when saving and when you try to recover it, compare a shorter string with a longer one.