dpkk8687 2011-05-14 02:36
浏览 92
已采纳

PHP:使用PDO从MySQL检索图像

I am refactoring some old code, including rewriting basic mysql queries to use PDO.

The following works brilliantly in all browsers and for all image types:

$query = 'SELECT image FROM image WHERE imageid=' . $image_id;
$result = mysql_query($query, $db_conn); querycheck($result);
header("Content-type: image");
echo mysql_result($result, 0);

Unfortunately, however I rewrite it using PDO, it doesn't work. I've been through the entire PDO documentation and the standard web search, but none of the advice/solutions work.

How can one easily fetch and image from MySQL using PDO and display it?

Edit 1:

Matthew Ratzloff gives what should be the obvious answer below, but it does not work. Here is the actual code that I test using PDO (and I have tried many variants/parameters):

$connectstring_temp = 'mysql:host=' . $A . ';dbname=' .$B;
$dbh_temp = new PDO($connectstring_temp, $login, $password);
#$dbh_temp->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
#$dbh_temp->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY,true);

$sql = "SELECT image FROM image WHERE imageid=" . $image_id;
$query = $dbh_temp->prepare($sql);
$query->execute();

$query->bindColumn(1, $image, PDO::PARAM_LOB);
$query->fetch(PDO::FETCH_BOUND);
header("Content-Type: image");
echo $image;

I've kept the same syntax, although for the final code $image_id needs to be passed as a parameter. The code above does NOT work. PDO works fine for all other queries of all types.

  • 写回答

4条回答 默认 最新

  • douzai1074 2011-05-14 03:09
    关注

    You need to paramaterize the imageid value and bind the parameter to PDO::PARAM_LOB:

    $sql = "SELECT image FROM image WHERE imageid=:id";
    $query = $db_conn->prepare($sql);
    $query->execute(array(':id' => $image_id));
    
    $query->bindColumn(1, $image, PDO::PARAM_LOB);
    $query->fetch(PDO::FETCH_BOUND);
    header("Content-Type: image");
    echo $image;
    

    Of course, you'll also want to specify the complete, correct content type (e.g., image/png).

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?