试图从MySQL数据库中以PHP显示图像

I attempted to display the image using PHP with the following code

<?php
header('Content-type: image/png');
 $port = "*";
 $server = "*:".$port;
 $dbname ="*";
 $user = "*";

 $conn = mysql_connect ("$server", "$user", "$pass") or die ("Connection
 Error or Bad Port");

mysql_select_db($dbname) or die("Missing Database");


    $speakerPic = $_POST['speakerPic'];
    $query = "SELECT Speaker.speaker_picture AS image FROM  Speaker JOIN Contact c USING(contact_id) 
    WHERE c.lname = '";
    $query .= $speakerPic."';";


$result = mysql_query($query,$dbname); 
$result_data = mysql_fetch_array($result, MYSQL_ASSOC);

echo $result_data['image'];   
?>

I keep on receiving this error, The image “.../query2.php” cannot be displayed because it contains errors.

Sorry to keep on bugging you guys, but can anyone tell what the problem is?

Not going to lie, there is a lot of bad with the OP code.

  1. You should be pulling images from the database by id, not some string
  2. You are not sanitizing the var being used in the query
  3. You are not serving a default image if one doesn't exist
  4. Also, I would suggest storing file uris in your database, not the actual image (blob). You should store a pointer to an image on your filesystem.

Not going to clean up the code too much, just make it less bad. I'd suggest something along these lines (untested):

// Utility.php
class Utility
{
    /**
     *
     * @param mixed $id is abstract, could be name or an actual id
     * @return string?
     */
    public static function getImage($id)
    {
        try {
            $port = "*";
            $server = "*:".$port;
            $dbname ="*";
            $user = "*";

            $conn = mysql_connect ("$server", "$user", "$pass");

            if (!$conn) {
               throw new Exception("Connection Error or Bad Port");
            }

            if (!mysql_select_db($dbname)) {
                throw new Exception("Missing Database");
            }

            $query = "SELECT Speaker.speaker_picture AS image FROM  Speaker JOIN Contact c USING(contact_id) WHERE c.lname = " . mysql_real_escape_string($id). ";";

            $result = mysql_query($query,$dbname); 
            $result_data = mysql_fetch_array($result, MYSQL_ASSOC);

            if (!isset($result_data['image'])) {
                throw new Exception('Image not found');
            }

            echo $result_data['image'];

         } catch Exception($e) {

             error_log($e->getMessage();

             return file_get_contents('/path/to/some/default/image.png');
         }   
    }
}

// image.php
require_once 'Utility.php';

header('Content-type: image/png');
ob_start();
Utility::getImage($_POST['speakerPic']);
$image = ob_get_flush();

echo $image;