Php pdo插入查询

时间:2013-08-30 13:27:17

标签: php mysql pdo

我需要在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)");

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

2 个答案:

答案 0 :(得分: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();

?>

答案 1 :(得分:2)

你可以这样试试。

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