尝试将图像上传到数据库,然后从中显示。得到一个致命的错误

时间:2016-05-13 07:13:34

标签: php mysql

错误:

  

致命错误:未捕获错误:在C:\ xampp \ htdocs \ FinalProject \ upload-profilePic.php中调用boolean上的成员函数bind_param():22堆栈跟踪:#0 {main}抛出C:..

我的代码:

上传图片

<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
if (file_exists($_FILES['upload_file']['tmp_name'])) {
    // get temp name and file name
    $tmpName = $_FILES['upload_file']['tmp_name'];
    $fileName = $_FILES['upload_file']['name'];
    $type = $_FILES['upload_file']['type'];

    $handler = fopen($tmpName, 'r'); // opens image file stream
    $data = fread($handler, filesize($tmpName)); // read byte data
    fclose($handler); // close image file stream

    $stmt = $con->prepare('insert into images (image_type,
        filename, image_data) values(?, ?, ?)');
    $stmt->bind_param('sss', $type, $fileName, $data);
    $stmt->execute();
    $result = $stmt->get_result();
    if (!$result) {
        echo $con->error;
    }
  }
}

$result = $con->query('select * from images');
if ($result) {
    foreach ($result as $img) {
        $name = $img['filename'];
        $id = $img['image_id'];
        $url = "get-profilePic.php?id=$id";
        echo "<h3>$name</h3>";
        echo "<img src=\"$url\" alt=\"$name\" />\n\n";
    }
}
?>

获取图片

<?php

$imageId = $_GET['id'];
$result = $con->query("select * from images
where image_id = $imageId");

if ($result) { 
    $image = $result->fetch_object();
    $type = $image->image_type;
    $data = $image->image_data;
    header('Content-Type: ' . $type);
    echo $data;
}
?>

2 个答案:

答案 0 :(得分:3)

通过考虑您的场景,问题在于:

$stmt = $con->prepare('insert into images (image_type, filename, image_data) values(?, ?, ?)');
$stmt->bind_param('sss', $type, $fileName, $data);

prepare()方法可以返回false,并且需要检查它为什么返回false,或者表名或列名(在SELECT或WHERE子句中)可能不正确?主要是您的查询中出现了一些错误。

另外,尝试使用类似$stmt ->error_list的内容来检查解析SQL时发生的错误。

答案 1 :(得分:0)

您的错误消息显示bind_param正在运行boolean。这通常是由$stmt false导致的,因为$con->prepare()失败了:

$stmt = $con->prepare('insert into images (image_type,
    filename, image_data) values(?, ?, ?)');
$stmt->bind_param('sss', $type, $fileName, $data);

我可以看到代码中未定义$con。你可以在这两行代码之前验证它是否存在吗?

var_dump($con);