Reputation: 7519
I am trying to encrypt the data values when inserting into MYSQL using AES_ENCRYPT and CBC encryption mode:
SET @@session.block_encryption_mode = 'aes-256-cbc';
If I insert the data directly in SQL, it successfully inserts without any problem.
However, if I insert through PHP using prepared statements (PDO), the data doesn't insert into the database and I receive no error and the lastInsertID returned is 0
.
If I remove the AES_ENCRYPT
part, it inserts the data successfully.
Complete code:
$sql .= "SET @IV = RANDOM_BYTES(16);";
$sql .= "INSERT INTO ". TABLE_NAME. " (record_created, name, dob, someinfo, iv)
VALUES (
NOW(),
:name,
AES_ENCRYPT(:dob, :key, @IV),
AES_ENCRYPT(:someinfo, :key, @IV),
@IV); ";
try {
$db = Employee::getConnection();
$stmt = $db->prepare($sql);
$stmt->bindParam(':key', $key);
$stmt->bindParam(':name', $employee->name);
$stmt->bindParam(':dob', $employee->dob);
$stmt->bindParam(':someinfo', $employee->someinfo);
$stmt->execute();
$employee->id = $db->lastInsertId();
$db = null;
echo json_encode($employee);
Upvotes: 3
Views: 4414
Reputation: 607
you can't fire multiple Querys seperateted with ";" like in PhpMyAdmin. This is a way, you may prefer:
<?php
$aeskey = '4ldetn43t4aed0ho10smhd1l';
$sql = "INSERT INTO ". TABLE_NAME. " (record_created, name, dob, someinfo)
VALUES (
NOW(),
:name',
AES_ENCRYPT(:dob, '".$aeskey."'),
AES_ENCRYPT(:someinfo, '".$aeskey."'));";
$db = Employee::getConnection();
$stmt = $db->prepare($sql);
$stmt->bindParam(':name', $employee->name);
$stmt->bindParam(':dob', $employee->dob);
$stmt->bindParam(':someinfo', $employee->someinfo);
$stmt->execute();
$employee->id = $db->lastInsertId();
$db = null;
echo json_encode($employee);
Upvotes: 3