是否可以将图像路径插入到数组中以及如何使用PHP进行操作?

是否可以将图像路径插入到数组中以及如何使用PHP进行操作?

问题描述:

I need help in inserting image path into arrays. Is it even possible? Firstly, I have created a table for accepting random comments from the user then inside that table I have a path for images that I want to call at the same time as the text. I have no problem displaying the texts such as username, password but when I add the path to it, it only displays the URL literally. How would I display the image?

Here is my PHP code:

<?php

require("admin.config.inc.php");

//initial query
$query = "Select * FROM adComments";

//execute query
try {
    $stmt   = $db->prepare($query);
    $result = $stmt->execute($query_params);
}
catch (PDOException $ex) {
    $response["success"] = 0;
    $response["message"] = "Database Error!";
    die(json_encode($response));
}

// Finally, we can retrieve all of the found rows into an array using fetchAll 
$rows = $stmt->fetchAll();


if ($rows) {
    $response["success"] = 1;
    $response["message"] = "Post Available!";
    $response["posts"]   = array();

    foreach ($rows as $row) {
        $post             = array();
    $post["post_id"]  = $row["post_id"];
    $post['img'] = 'http://www.stagconnect.com/StagConnect/admin/pictures/'.$row["image_name"];
    $post["username"] = $row["username"];
    $post["title"]    = $row["title"];
    $post["message"]  = $row["message"];
    $post["time"] = $row["time"];


        //update our repsonse JSON data
        array_push($response["posts"], $post);
    }

    // echoing JSON response
    echo json_encode($response);


} else {
    $response["success"] = 0;
    $response["message"] = "No Post Available!";
    die(json_encode($response));
}

?>

The only problem here is the post['img']. It doesn’t display an image. What other method can I try? Any help will do.

The fact that the variable name contains the word "img" means nothing. What you need to do is where you are processing the response from the Database into HTML, you need to specifically state that this is an image and you want it displayed as such.

<img src="value from post["img"]" alt="Image" height="50" width="50">

You can omit the width and height parameters if you don't need to restrict the size of the images.

Embedding an img tag inside the post string may work, but from a design point of view, you are then restricting what what you can do with the returned data.

A more flexible solution would be to separate the URL from the image name:

$post["img_url"] = 'http://www.stagconnect.com/StagConnect/admin/pictures/';
$post["image_name"] = $row["image_name"];

And then:

<img src="value from post["img_url"] plus value from post["image_name"]" alt="Image" height="50" width="50">

This would enable you to (if you wanted to) have the URL in the Database, and possibly have a different URL for each image. In other words, no hard-coding.