-2

我需要在 mysql 表中插入加密值,但是当我使用传统的 pdo 方法插入它时,插入的数据格式错误。例如:我插入 aes_encrypt(value, key) 代替插入加密值,将其作为字符串插入。

以下是代码:

$update = "insert into `$table` $cols values ".$values;
$dbh = $this->pdo->prepare($update);
$dbh->execute($colVals);

$arr = array("col"=>"aes_encrypt ($val, $DBKey)");

我知道我做错了,但找不到正确的方法。

4

2 回答 2

3

你快到了,这是一个简化的版本:

<?php

$sql = "insert into `users` (`username`,`password`) values (?, aes_encrypt(?, ?))";
$stmt = $this->pdo->prepare($sql);

// Do not use associative array
// Just set values in the order of the question marks in $sql
// $fill_array[0] = $_POST['username']  gets assigned to first ? mark
// $fill_array[1] = $_POST['password']  gets assigned to second ? mark
// $fill_array[2] = $DBKey              gets assigned to third ? mark

$fill_array = array($_POST['username'], $_POST['password'], $DBKey); // Three values for 3 question marks

// Put your array of values into the execute
// MySQL will do all the escaping for you
// Your SQL will be compiled by MySQL itself (not PHP) and render something like this:
// insert into `users` (`username`,`password`) values ('a_username', aes_encrypt('my_password', 'SupersecretDBKey45368857'))
// If any single quotes, backslashes, double-dashes, etc are encountered then they get handled automatically
$stmt->execute($fill_array); // Returns boolean TRUE/FALSE

// Errors?
echo $stmt->errorCode().'<br><br>'; // Five zeros are good like this 00000 but HY001 is a common error

// How many inserted?
echo $stmt->rowCount();

?>
于 2013-08-30T13:55:43.323 回答
2

你可以试试这样。

$sql = "INSERT INTO $table (col) VALUES (:col1)";
$q = $conn->prepare($sql);
$q->execute(array(':cols' => AES_ENCRYPT($val, $DBKey)));
于 2013-08-30T13:51:24.150 回答