Oby Saputra Oby Saputra - 1 month ago 6
PHP Question

how to get image url from database in php?

I have problem to show image url-link to my showdb.php


My current db record:

|_id_____|____name_____|_image|

|____1_____|__banana____|banana.jpg|

|____2_____|__aple______|apple.jpg |


What I want to do is how banana.jpg or under image column to be www.myhost.com/image/banana.jpg when it showed in record.php?

What I get right now :


{"posts":[
{
"name":"banana",
"image":banana.jpg}, // FROM THIS
{
"name":"apple",
"image":apple.jpg} // FROM THIS
]}




What I want :


{"posts":[
{
"name":"banana",<br>
"image":www.myhost.com/image/banana.jpg}, // BECOME THIS
{
"name":"apple",<br>
"image":www.myhost.com/image/apple.jpg} // BECOME THIS
]}






And this is my current code to show my db record:


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

foreach ($rows as $row) {

$post = array();
$post["name"] = $row["name"];
$post["image"] = $row["image"];


//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));
}


is posible to change those code?

or if any link to do that, I'm so pleased :))



Thank You, for your answer :))) *and sorry if my english is bad :)


============================================================


Solved by: @KhaledBentoumi



Just add

'www.yourhost.com/folder/'(dot)$row["image"]; => 'www.yourhost.com'.$row["image"];


but, it will change
/
to
\/
:
'www.yourhost.com\/folder\/file.jpg




add
JSON_UNESCAPED_SLASHES
, for example:

$url = 'http://www.example.com/';

echo json_encode($url), "\n";

echo json_encode($url, JSON_UNESCAPED_SLASHES), "\n";


happy coding guys! :))

Answer

Simply append www.myhost.com/image/ to your image entrie in the post array

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

foreach ($rows as $row) {

$post             = array();
$post["name"]  = $row["name"];
$post["image"]    = 'www.myhost.com/image/'.$row["image"]; // Append here


//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));
}
Comments