2013-08-30 57 views
-2

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

以下是代码:

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

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

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

+0

什么是插入的'传统PDO method'? '$ cols'和'$ values'的值是多少?什么是'$ colVals'? – andrewsi

+0

为什么不先学习Mysql的插入语法,然后是普通的PDO,然后才转向任何“加密插入”(我怀疑你需要)? –

+1

'$ values'和'$ colVals'是什么? –

回答

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

?> 
+0

感谢这样工作 – viv

2

你可以尝试这样。

$sql = "INSERT INTO $table (col) VALUES (:col1)"; 
$q = $conn->prepare($sql); 
$q->execute(array(':cols' => AES_ENCRYPT($val, $DBKey))); 
+3

'AES_ENCRYPT'是一个MySQL函数,不是PHP。所以,你靠近但没有雪茄。我想你想要:'VALUES(AES_ENCRYPT(:val,:dbkey))' –