Display Images From a Local Directory in PHP - php

I am trying to get the File Name of the Images form database and want to insert in a page. I am inserting images to a local folder and store the names in the database. Need to retrieve it and.
<?php
global $DBConnect;
$Query = "SELECT * FROM posts ORDER BY datetime DESC ";
$Execute = mysqli_query($DBConnect,$Query);
while ($DataRows = mysqli_fetch_array($Execute)){
$PostID = $DataRows["id"];
$DateTime = $DataRows["datetime"];
$Category = $DataRows["category"];
$Author = ["author"];
$Image = ["image"];
$Post = $DataRows["post"];
?>
<div class="thumbnail">
<img src="uploads/<?php echo $Image;?>">
</div>
<?php }?>

I didn't fetch the image using $DataRows. Its was my Mistake..!
$Image = $DataRows["image"];

Related

How to display images from folder and fetch path from database using AJAX?

I already have modal where I fetched the image path from the database and it is shown in the modal.
The PHP code to display images:
<?php
include_once '../../php/connection.php';
$query = "SELECT * FROM img_info LEFT JOIN estate_infos ON img_info.estate_infos_id = estate_infos.id
where img_info.estate_infos_id = $mdoalid";
$stmt = $dbcon->prepare($query);
$stmt->execute();
$count = $stmt->rowCount();
$datas = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($datas as $key => $data)
{
$pic = $data['image'];
?>
<img src="../<?php echo $pic ?>" width="360" height="150">
<a data-toggle="modal" data-target="#delete-modal" data-imgid="<?php echo $data['img_id']; ?>">
<i class="far fa-times-circle fa-2x" aria-hidden="true" style="color:red"></i>
</a>
<?php
}
?>
The Output of the above code is
How can I implement this in AJAX?
PS: I just need to display the image, not upload and display.
You can achieve your purpose by creating a script to find and return the data. After getting the data you can build your list with javascript.
<?php
include_once '../../php/connection.php';
$query = "SELECT * FROM img_info LEFT JOIN estate_infos ONimg_info.estate_infos_id = estate_infos.id where img_info.estate_infos_id = $mdoalid";
$stmt = $dbcon->prepare($query);
$stmt->execute();
$count = $stmt->rowCount();
$datas = $stmt->fetchAll(PDO::FETCH_ASSOC);
// Turning your array into json
echo json_encode($datas);
?>
On this following page, you can understand how to display your data with javascript.
https://jsfiddle.net/onury/kBQdS/

data from sql database not showing properly in php

hi i got a sql database table which has some images and some description. i need to be able to display everything but is not working properly. i got 2 different pages. where all the database staff is and the index page. here is the function from the first page
function get_image() {
global $db;
$query = 'SELECT * FROM table ';
try {
$statement = $db->prepare($query);
$statement->execute();
$result = $statement->fetchAll();
$statement->closeCursor();
return $result;
} catch (PDOException $e) {
$error_message = $e->getMessage();
display_db_error($error_message);
}
Here is index.php:
//on the index page i set up an array to display all the images but all i get is a 404 not found. this is the index page
<?php
require_once('model/database.php');
require_once('model/image_db.php');
// Set the array to display the images
$image_ids = array(1,2,3,4,5);
$images = array();
foreach ($image_ids as $image_id) {
$image = get_image();
$images[] = $image; // add images to array
}
// Display the home page
include('home_view.php');
?>
and on the home page i display everything but is not showing.. any ideas
<table>
<?php foreach ($images as $image) :
// Get image data
$imaget_price = $image['Price'];
$description = $image['description'];
// Get first paragraph of description
$description = add_tags($description);
$i = strpos($description, "</p>");
$description = substr($description, 3, $i-3);
?>
<tr>
<td id="image_column">
<img src="images/<?php echo $image['ID']; ?>.jpg"
alt=" ">
</td>
</tr>
<?php endforeach; ?>
</table>
?>
Edit:
You are binding values to a query that takes no values.
$statement->bindValue(1, $image_id);
You probably want something like this:
$query = 'SELECT * FROM table WHERE image_id = ?';

How to display image from database using php [duplicate]

This question already has answers here:
How to retrieve images from MySQL database and display in an html tag
(4 answers)
Closed 1 year ago.
I am trying to display an image coming from the database and I was not able to display the image .but its showing like this user-1.jpg Please see my code can one guide me how to display the image.
$sqlimage = "SELECT image FROM userdetail where `id` = $id1";
$imageresult1 = mysql_query($sqlimage);
while($rows = mysql_fetch_assoc($imageresult1))
{
$image = $rows['image'];
print $image;
}
Displaying an image from MySql Db.
$db = mysqli_connect("localhost","root","","DbName");
$sql = "SELECT * FROM products WHERE id = $id";
$sth = $db->query($sql);
$result=mysqli_fetch_array($sth);
echo '<img src="data:image/jpeg;base64,'.base64_encode( $result['image'] ).'"/>';
For example if you use this code , you can load image from db (mysql) and display it in php5 ;)
<?php
$con =mysql_connect("localhost", "root" , "");
$sdb= mysql_select_db("my_database",$con);
$sql = "SELECT * FROM `news` WHERE 1";
$mq = mysql_query($sql) or die ("not working query");
$row = mysql_fetch_array($mq) or die("line 44 not working");
$s=$row['photo'];
echo $row['photo'];
echo '<img src="'.$s.'" alt="HTML5 Icon" style="width:128px;height:128px">';
?>
<?php
$connection =mysql_connect("localhost", "root" , "");
$sqlimage = "SELECT * FROM userdetail where `id` = '".$id1."'";
$imageresult1 = mysql_query($sqlimage,$connection);
while($rows = mysql_fetch_assoc($imageresult1))
{
echo'<img height="300" width="300" src="data:image;base64,'.$rows['image'].'">';
}
?>
You need to do this to display image
$sqlimage = "SELECT image FROM userdetail where `id` = $id1";
$imageresult1 = mysql_query($sqlimage);
while($rows=mysql_fetch_assoc($imageresult1))
{
$image = $rows['image'];
echo "<img src='$image' >";
echo "<br>";
}
You need to use html img tag.
put you $image in img tag of html
try this
echo '<img src="your_path_to_image/'.$image.'" />';
instead of
print $image;
your_path_to_image would be absolute path of your image folder like eg: /home/son/public_html/images/ or as your folder structure on server.
Update 2 :
if your image is resides in the same folder where this page file is exists
you can user this
echo '<img src="'.$image.'" />';
instead of print $image; you should go for print "<img src=<?$image;?>>"
and note that $image should contain the path of your image.
So,
If you are only storing the name of your image in database then instead of that you have to store the full path of your image in the database like /root/user/Documents/image.jpeg.
Simply replace
print $image;
with
echo '<img src=".$image." >';
$sqlimage = "SELECT image FROM userdetail where `id` = $id1";
$imageresult1 = mysqli_query($link, $sqlimage);
while($rows=mysqli_fetch_assoc($imageresult1))
{
echo "<img src = 'Image/".$row['image'].'" />';
}
<?php
$conn = mysql_connect ("localhost:3306","root","");
$db = mysql_select_db ("database_name", $conn);
if(!$db) {
echo mysql_error();
}
$q = "SELECT image FROM table_name where id=4";
$r = mysql_query ("$q",$conn);
if($r) {
while($row = mysql_fetch_array($r)) {
header ("Content-type: image/jpeg");
echo $row ["image"];
}
}else{
echo mysql_error();
}
?>
sometimes problem may occures because of port number of mysql server is incoreect to avoid it just write port number with host name like this "localhost:3306"
in case if you have installed two mysql servers on same system then write port according to that
in order to display any data from database please make sure following steps
1.proper connection with sql
2.select database
3.write query
4.write correct table name inside the query
5.and last is traverse through data
put this code to your php page.
$sql = "SELECT * FROM userdetail";
$result = mysqli_query("connection ", $sql);
while ($row = mysqli_fetch_array($result,MYSQLI_BOTH)) {
echo "<img src='images/".$row['image']."'>";
echo "<p>".$row['text']. "</p>";
}
i hope this is work.

Delete image and copy from gallery

I have a gallery that I'm able to upload images with a title and a short description about the image. I store the images in a folder on my ftp and the data in a database. Here is a screen shot of the database.
I want to give my client a little more control over the gallery by allowing them to update the gallery and delete posts in the gallery. Right now I want to focus on the DELETING part.
I'm using the following code to try and delete the images/post by trying to select by id and delete.
When executing the delete script on the site I get no errors on the page or on my ftp, but the image does not delete.
The end result I'm looking for would be to have the row deleted from the table and the image deleted from the ftp.
I'm very new to php and know I need to learn much more about it, but if someone could help out I would appreciate it. I apologize for the code dump, but not sure how to ask the question without showing what I'm working with.
DELETE CODE:
<?php
//including the database connection file
include($_SERVER['DOCUMENT_ROOT'] . "/connections/dbconnect.php");
//getting id of the data from url
$id = isset($_GET['id']) && $_GET['id'] == $row['id'];
//deleting the row from table
$result=mysql_query("DELETE FROM images where id='$id' limit 1;");
//redirecting to the display page (index.php in our case)
echo '<table align="center" width="100%" height="100%" border="0"><tr align="center" valign="center"><td><h2>Deleting Image</h2></td></tr></table>';
echo '<meta http-equiv="refresh" content="5;URL=/admin/modify-gallery.php">';
?>
This is the code I'm using to to access the image on the modify-gallery page
modify-gallery code:
include($_SERVER['DOCUMENT_ROOT'] . "/connections/dbconnect.php");
/* be safe, not sorry */
foreach ($_REQUEST as $k => $v) {
$_REQUEST[$k] = mysql_real_escape_string($v);
}
/* take cat from url if exists */
$category = #$_REQUEST["category"] ? $_REQUEST["category"] : null;
$images = mysql_query(
$category ?
sprintf(
"SELECT * FROM images WHERE data_type = '%s'",
$category
) :
"SELECT * FROM images"
);
if ($images) {
$total = mysql_num_rows($images);
if ($total) {
$per = 12;
$page = #$_REQUEST["page"] ? $_REQUEST["page"] : 1;
$pages = ceil($total/$per);
}
mysql_free_result($images);
}
?>
and then this is used to display the images/posts and lists the delete and update button..(same page)
<div class="row">
<ul id="stage" class="portfolio-4column">
<?php
if ($category) {
$images = mysql_query(sprintf(
"SELECT * FROM images WHERE data_type = '%s' ORDER BY id DESC LIMIT %d, %d",
$category, ($page - 1) * $per, $per
));
} else $images = mysql_query(sprintf(
"SELECT * FROM images ORDER BY id DESC LIMIT %d, %d",
($page - 1) * $per, $per
));
while ($image=mysql_fetch_array($images))
{
?>
<li data-id="id-<?=$image["id"] ?>" data-type="<?=$image["data_type"] ?>">
<div class="grid_3 gallerybox-admin">
<div class="overallheight-admin">
<div class="gallerybox-admin"><a class="fancybox" rel="<?=$image["data_type"] ?>" href="http://<?php echo $_SERVER['SERVER_NAME']; ?>/images/gallery/<?=$image["file_name"] ?>" title="<?=$image["title"] ?>">
<img src="http://<?php echo $_SERVER['SERVER_NAME']; ?>/images/gallery/<?=$image["file_name"] ?>" alt="<?=$image["title"] ?>" class="max-img-border"></a></div>
<div class="galleryh"><?=$image["title"] ?></div>
<div class="galleryp"><?=$image["description"] ?></div>
</div>
<div class="grid_1"><h4 class="btn-green">Delete</h4></div>
<div class="grid_1"><h4 class="btn-green">Update</h4></div>
</div>
</li>
<?php
}
?>
</ul>
</div>
Code from Stack Overflow (Currently Using):
<?php
//including the database connection file
include($_SERVER['DOCUMENT_ROOT'] . "/connections/dbconnect.php");
//getting id of the data from url
$id = isset($_GET['id']) && $_GET['id'] == $row['id'];
//Select image_name(if not known)
$img = mysql_query("Select file_name from images where id=\"$id\"");
$img_res = mysql_fetch_array($img);
$filename = $img_res[0];
unlink($_SERVER['DOCUMENT_ROOT'] . "/images/gallery/" . $filename);
//deleting the row from table
$result=mysql_query("DELETE FROM images where id=\"$id\" limit 1;");
//redirecting to the display page
echo '<table align="center" width="100%" height="100%" border="0"><tr align="center" valign="center"><td><h2>Deleting Image</h2></td></tr></table>';
echo '<meta http-equiv="refresh" content="5;URL=/admin/modify-gallery.php">';
?>
fix this in delete button html, to pass the file name by the url
<h4 class="btn-green">Delete</h4></div>
In your remove.php
include("/connections/dbconnect.php");
$filename = isset($_GET['value']) ? $_GET['value'] : NULL;
if (!empty($filename)) {
$delete = unlink("images/gallery/" . $filename);
if($delete){
$result = mysql_query("DELETE FROM images where file_name="'. mysql_real_escape_string($filename)."' limit 1;")";
header("Location:succes_page.php");
}else{
header("Location:failure_page.php");
}
}else{
header("Location:failure_page.php");
}
side note try to update your mysql_* functions to PDO or mysqli
"The end result I'm looking for would be to have the row deleted from the table and the image deleted from the ftp."
the row deleted from the table ✓
But you still need to remove the actual file from your server to do so use unlink($fileName);
//getting id of the data from url
$id = isset($_GET['id']) && $_GET['id'] == $row['id'];
// Delete the file from the server
unlink($_SERVER['DOCUMENT_ROOT'] . "{Path Where Your Images stored}" . $row['file_name']);
//deleting the row from table
$result=mysql_query("DELETE FROM images where id='$id' limit 1;");
As you can see I used the $row['file_name'] to get the file name from you database (good to show us your table structure)
To delete a file from the ftp you should use
unlink(filename with complete path);
Complete Code:
//Change Delete code to following
<?php
//including the database connection file
include($_SERVER['DOCUMENT_ROOT'] . "/connections/dbconnect.php");
//getting id of the data from url
$id = isset($_GET['id']) && $_GET['id'] == $row['id'];
//Select image_name(if not known)
$img = mysql_query("Select image_name(your column) from images where id=\"$id\"");
$img_res = mysql_fetch_array($img);
$filename = $img_res[0];
unlink("path to file".$filename);
//deleting the row from table
$result=mysql_query("DELETE FROM images where id=\"$id\" limit 1;");
//redirecting to the display page (index.php in our case)
echo '<table align="center" width="100%" height="100%" border="0"><tr align="center" valign="center"><td><h2>Deleting Image</h2></td></tr></table>';
echo '<meta http-equiv="refresh" content="5;URL=/admin/modify-gallery.php">';
?>

Joomla TPlancer component adding new field and displaying

I have the TPLancer component for Joomla installed on my site and I am trying to add some more information to the profile page of both the Freelancer and the Buyer. I am no genius with PHP or mySQL but can kind of bluff my way thru usually.
The information currently displayed on the profile pages is just data pulled from the database. I have added a new ‘website’ row in the database and have entered some data into the database but I can’t seem to get it to display. I thought it would just be something like echo $row->website; because echo $row->categories; works and so does echo $row->company; and they are all in the same table.
There is something happening that is obviously way above my head. Below I have pasted a section of the code from the tplancer.php file which contains the function for what I am trying to target.
Below that is some code from the tplancer.html.php file which displays the actual HTML on the page.
I hope someone can help and I hope I don’t sound too dumb! Cheers
function showLancerInfo($option)
{
global $mainframe;
$user =& JFactory::getUser();
$db =& JFactory::getDBO();
$lancer_id = JRequest::getVar('id', 0, 'get', 'int');
$is_lancer = isLancer($user->id);
$is_buyer = isBuyer($user->id);
$query = "select id FROM #__glance_lancer where userid =".$lancer_id;
$db->setQuery( $query );
$id = $db->loadResult();
if(!$id)
{
echo "Freelancer not found!";
return;
}
$query = "select username FROM #__users where id =".$lancer_id;
$db->setQuery( $query );
$username = $db->loadResult();
$row =& JTable::getInstance('lancer','Table');
$row->load($id);
$query = "select * FROM #__glance_projects where chosen =".$lancer_id." ORDER BY id desc LIMIT 10";
$db->setQuery( $query );
$projects = $db->loadObjectList();
$query = "select * FROM #__glance_bids where userid=".$lancer_id." order by id desc LIMIT 10 ";
$db->setQuery( $query );
$bids = $db->loadObjectList();
HTML_front_glance::showLancerInfo($option,$row,$projects,$bids,$username);
}
function showLancerInfo($option,$row,$projects,$bids,$username)
{
global $mainframe, $option;
$user =& JFactory::getUser();
$lancer_info = getUserInfo($row->userid);
?>
<!-- /////////////////////// FREELANCER PROFILE PAGE /////////////////////// -->
<?php
$img = JPATH_SITE.DS.'images'.DS.'glance'.DS.$row->userid.'.jpg';
if(file_exists($img)) {
$img = JURI::base().'images/glance/'.$row->userid.'.jpg';
echo '<img class="profile_logo" src="'.$img.'" alt="Logo" />';
}
else
{
$img = JURI::base().'components/com_glance/images/noimage.jpg';
echo '<img class="profile_logo" src="'.$img.'" alt="Logo"/>';
}
?>
<div class="profile_info">
<h1><?php echo $lancer_info['username'] ?><?php if($row->special=='y') {?>
<img src="components/com_glance/images/featured.png" alt="Featured" class="feat_lancer" />
<?php } ?></h1>
<h3><?php echo $row->company ;?></h3>
<p><?php echo $row->categories ; ?></p>
<p>Website: <?php echo $row->website; ?></p>
<p>Hourly Rate US $<?php echo $row->rate; ?></p></code>
Trying look for a folder in the component called "tables". Find the correct file, it should be called "lancer", in there that defines the table variables for the table you want and add the new variables you wish to display - e.g.
...
var $website = null;
...
Then you will be able to use, as you said, $row->website.
The clue you are looking for in the model function is this line:
$row =& JTable::getInstance('lancer','Table');
I hope that solves your problem! Good luck!

Categories