PDO does not rewind bound stream
I am using PHP PDO and MySQL.
I am trying to execute a ON DUPLICATE KEY UPDATE
query,
binding stream to two placeholders in the query.
Here is a code example:
<?php
/**
* @param PDO $pdo
* @param string $fileName
* @param resource $fileContent
*/
function persistFromStream(PDO $pdo, string $fileName, $fileContent): void
{
$query = <<<SQL
INSERT INTO files (name, content)
VALUES (:name, :content)
ON DUPLICATE KEY UPDATE content = :contentSecondTime
SQL;
$statement = $pdo->prepare($query);
$statement->bindParam(':name', $name);
$statement->bindParam('content', $fileContent, PDO::PARAM_LOB);
$statement->bindParam('contentSecondTime', $fileContent, PDO::PARAM_LOB);
$statement->execute();
}
Insert works fine.
"ON DUPLICATE" logic does not work fine: it writes empty string (''
) into content
column.
I suspect that this happens because PDO does not rewind my stream ($fileContent
) when using it second time (in the "DUPLICATE
clause").
If I copy the stream, both INSERT and ON DUPLICATE will work fine:
/**
* @param PDO $pdo
* @param string $fileName
* @param resource $fileContent
* @return void
*/
function persistFromStreamWithCopying(PDO $pdo, string $fileName, $fileContent): void
{
$contentCopy = fopen('php://temp', 'r+');
stream_copy_to_stream($fileContent, $contentCopy);
rewind($fileContent);
rewind($contentCopy);
$query = <<<SQL
INSERT INTO files (name, content)
VALUES (:name, :content)
ON DUPLICATE KEY UPDATE content = :contentSecondTime
SQL;
$statement = $pdo->prepare($query);
$statement->bindParam(':name', $fileName);
$statement->bindParam('content', $fileContent, PDO::PARAM_LOB);
$statement->bindParam('contentSecondTime', $contentCopy, PDO::PARAM_LOB);
$statement->execute();
}
The question is: Can I bind a single stream twice in a query, so PDO rewinds it somehow?
Thank you for your attention.
Kind regards.