php pdo插入查询 [英] Php pdo insert query

查看:61
本文介绍了php pdo插入查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I need to insert encrypted values in mysql table, but when I use traditional pdo method to insert its inserting the data in wrong format. ex: I insert aes_encrypt(value, key) in place of inserting encrypted value its inserting this as string.

以下是代码:

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

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

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

I know i am doing it wrong, but not able to find correct way.

推荐答案

您快到了,这是简化版本:

You are almost there, here is a simplified version:

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

?>

这篇关于php pdo插入查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆