开发者

MySQL INSERT from a SELECT with PDO

开发者 https://www.devze.com 2023-03-14 03:54 出处:网络
I have a strange behaviour using PHP PDO for a INSERT from a SELECT query. Testing the query directly in MySQL it works well, I get my row inserted :

I have a strange behaviour using PHP PDO for a INSERT from a SELECT query. Testing the query directly in MySQL it works well, I get my row inserted :

INSERT INTO sessionid (enc_id, enc_pass, enc_date) 
SELECT AES_ENCRYPT(username, 'aeskey'), AES_ENCRYPT(pwd, 'aeskey'), 
DA开发者_如何学运维TE_ADD(NOW(), INTERVAL 15 SECOND) FROM users WHERE username = 'a_user_name';

But using PDO, I have one row per user inserted at once (279 rows) .... Here is the PHP :

$sql_enc = '
    INSERT INTO sessionid (enc_id, enc_pass, enc_date) 
        (SELECT AES_ENCRYPT(username, :aeskey), AES_ENCRYPT(pwd, :aeskey), DATE_ADD(NOW(), INTERVAL 15 SECOND) FROM users WHERE username = :username)
';
$res_enc = $pdo->prepare($sql_enc);
$res_enc->bindParam(':aeskey', $aeskey);
$res_enc->bindParam(':username', $username);
$res_enc->bindParam(':pwd', $username);
$res_enc->execute();
$res_enc = null;

What am I missing? I'm almost sure it's nothing but can't make it insert that single row.

Thank you.

fabien.


Not that it is the probable problem, but you put a username in the password field in your code. In your query you insert the aeskey there. It is the only difference I can spot.


Look at the PHP Documentation for PDO::bindParam. One user there suggested:

...you must use each parameter once and only once...

So, you used username and aeskey twice. Do it this way:

$sql_enc = '
    INSERT INTO sessionid (enc_id, enc_pass, enc_date) 
        (SELECT AES_ENCRYPT(:username1, :aeskey1), AES_ENCRYPT(:pwd, :aeskey2), DATE_ADD(NOW(), INTERVAL 15 SECOND) FROM users WHERE username = :username2)
';
$res_enc = $pdo->prepare($sql_enc);
$res_enc->bindParam(':aeskey1', $aeskey);
$res_enc->bindParam(':aeskey2', $aeskey);
$res_enc->bindParam(':username1', $username);
$res_enc->bindParam(':username2', $username);
$res_enc->bindParam(':pwd', $username);
$res_enc->execute();
$res_enc = null;
0

精彩评论

暂无评论...
验证码 换一张
取 消