2011-12-09 75 views
2

显示在PHP图像我试图使用PHP用下面的代码试图从MySQL数据库

<?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']; 
?> 

我保持在接收此错误,所述的图像“,以显示图像.../query2.php “不能显示,因为它包含错误。

对不起,继续扰乱你们,但谁能告诉问题是什么?

+1

小心任何输出任何来自引入的脚本。请务必消除标签之外的任何内容。实际上,您应该完全删除您的关闭?>标记以确保它后面没有空格。确保你的脚本没有回应某种错误信息。 –

+0

这些错误到底是什么? – mugetsu

+0

使用浏览器的开发人员工具查看图像的HTTP请求。特别要注意'Content-Length'标题。看看这是不是图像的大小(我认为你已经知道)的几个不同的图像不同。如果不同,有什么区别?不同的图像的差异是相同还是保持不变? – Jon

回答

0

不会说谎,OP代码有很多不好的地方。

  1. 你应该从数据库ID来拉动的图像,而不是一些字符串
  2. 你没有消毒的VAR在查询中使用
  3. 你是不是服务的默认图像,如果不存在
  4. 另外,我会建议存储文件uris在你的数据库中,而不是实际的图像(blob)。你应该在你的文件系统上存储一个指向图像的指针。

不打算清理代码太多,只是让它不那么糟糕。我会建议沿着这些线(未经测试)的东西:

// 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; 
+0

谢谢。我绝对是一个初学者,我会试着围绕你的代码绕过我的头脑。我真的很感激你花时间,这个社区是真棒。 – user1087799

+0

@ user1087799:不用担心......并不意味着过分苛刻。 –