简体   繁体   中英

Inserting into mysql database AES_ENCRYPT using PHP PDO

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); 

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); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM