如何从数据库路径显示图像

时间:2017-04-24 12:14:13

标签: php image

我有一个MVC模式,我试图从数据库路径显示图像。 以下是我的观点:

<div class="col-md-8">
    <h1 ><?php echo htmlspecialchars( $results['task']->username )?></h1>
    <p><?php echo htmlspecialchars( $results['task']->email )?></p>
    <p><?php echo $results['task']->text?></p>
    <img src="<?php echo $results['task']->imagePath?>" />

    <p>Published on <?php echo date('j F Y', $results['task']->publicationDate)?></p>

    <p><a href=".?action=home">Return to Homepage</a></p>
</div>

和控制器:

<?php

require( "config/config.php" );
$action = isset( $_GET['action'] ) ? $_GET['action'] : "";

switch ( $action ) {
  case 'viewTask':
    viewTask();
    break;
}

function viewTask() {
  if ( !isset($_GET["taskId"]) || !$_GET["taskId"] ) {
    homepage();
    return;
  }

  $results = array();
  $results['task'] = Task::getById( (int)$_GET["taskId"] );
  $results['pageTitle'] = $results['task']->username . " ";
  require( TEMPLATE_PATH . "/viewTask.php" );
}

在Task类中的getById函数:

class Task
{
  // Свойства
  public $id = null;

  public $username = null;
  public $email = null;

  public $text = null;
  public $publicationDate = null;

  public function __construct( $data=array() ) {
    if ( isset( $data['id'] ) ) $this->id = (int) $data['id'];
    if ( isset( $data['username'] ) ) $this->username = $data['username'];
    if ( isset( $data['email'] ) ) $this->email = $data['email'];
    if ( isset( $data['text'] ) ) $this->text = $data['text'];
    if ( isset( $data['publicationDate'] ) ) $this->publicationDate = (int) $data['publicationDate'];
    if ( isset( $data['status'] ) ) $this->status = (int) $data['status'];
  }

  public static function getById( $id ) {
    $conn = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
    $sql = "SELECT *, UNIX_TIMESTAMP(publicationDate) AS publicationDate FROM tasks WHERE id = :id";
    $st = $conn->prepare( $sql );
    $st->bindValue( ":id", $id, PDO::PARAM_INT );
    $st->execute();
    $row = $st->fetch();
    $conn = null;
    if ( $row ) return new Task( $row );
  }
}

如何获取图像并在页面上显示?感谢

2 个答案:

答案 0 :(得分:0)

在Task类中创建一个函数:

public function getImage($id){ 
   $path = "SELECT imgPath FROM tasks WHERE id = :id";
   return $path;
}

还要将其添加到您的HTML中:

<img src="<?php echo $results['task']->getImage($results['task']->id); ?>" />

你有没有尝试过什么?发布

答案 1 :(得分:0)

你错过了尝试这个

的东西
<img src="<?php echo $results['task']->imagePath; ?>" />