2013-08-30 187 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))' –