Why am i only finding image path when retrieving images from database - php

Im trying to retrieve images from my database by using php, my code is connected to the database, all the other information is being retrieved ok, however it is just showing my image path when trying to retrieve images! Anyone know what im doing wrong so i can get my images to show up?
$query = "SELECT p.name, p.image, p.price, p.description, p.category_id, ci.quantity
FROM products p
LEFT JOIN cart_items ci
ON p.id=ci.product_id
WHERE p.id=?
LIMIT 0,1";
$stmt = $con->prepare( $query );
$stmt->bindParam(1, $id);
$stmt->execute();
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$name = $row['name'];
$image = $row['image'];
$price = $row['price'];
$description = $row['description'];
$category_id = $row['category_id'];
$quantity = $row['quantity'];
?>
<!-- HTML form for updating a product -->
<tr>
<td style='width:30%;'>Name<?php echo "<div class='product-id' style='display:none;'>{$id}</div>"; ?></td>
<td class='product-name' style='width:70%;'><?php echo $name; ?></td>
</tr>
<tr>
<td>Image</td>
<td><?php echo $image; ?></td>
</tr>

As now you have you image path, you can show up the image in html something like: <img src="<?php echo $row['image']; ?>" >. Your are doing so because this is the convenient way store/retrieve an image form Database by using their path. Instead of storing the path of the image, storing the whole binary image file in database make it more complex and less efficient.

Related

PHP giving specific item access to admins

So I have this food ordering system where each admin uploads his or her food from the backend and users can browse through those food from the frontend, a simple program. But what I want is that an admin should not be able to view or update the food from another admin as right now any of the admins can view and update all the food that are uploaded on the backend. What I want is only a specific admin only viewing and updating his or her added food items.
Attached below is the snippet and picture of the food view and update page where it displays all foods and can update them.
FYI the code is in PHP and the backend is SQL in phpMyAdmin
Please do let me if there are any confusions in my explanation.
<?php include('partials/menu.php'); ?>
<div class="main-content">
<div class="wrapper">
<h1>Manage Food</h1>
<br /><br />
<!-- Button to Add Admin -->
Add Food
<br /><br /><br />
<?php
if(isset($_SESSION['add']))
{
echo $_SESSION['add'];
unset($_SESSION['add']);
}
if(isset($_SESSION['delete']))
{
echo $_SESSION['delete'];
unset($_SESSION['delete']);
}
if(isset($_SESSION['upload']))
{
echo $_SESSION['upload'];
unset($_SESSION['upload']);
}
if(isset($_SESSION['unauthorize']))
{
echo $_SESSION['unauthorize'];
unset($_SESSION['unauthorize']);
}
if(isset($_SESSION['update']))
{
echo $_SESSION['update'];
unset($_SESSION['update']);
}
?>
<table class="tbl-full">
<tr>
<th>S.N.</th>
<th>Title</th>
<th>Price</th>
<th>Image</th>
<th>Featured</th>
<th>Active</th>
<th>Actions</th>
</tr>
<?php
//Create a SQL Query to Get all the Food
$sql = "SELECT * FROM tbl_food";
//Execute the qUery
$res = mysqli_query($conn, $sql);
//Count Rows to check whether we have foods or not
$count = mysqli_num_rows($res);
//Create Serial Number VAriable and Set Default VAlue as 1
$sn=1;
if($count>0)
{
//We have food in Database
//Get the Foods from Database and Display
while($row=mysqli_fetch_assoc($res))
{
//get the values from individual columns
$id = $row['id'];
$title = $row['title'];
$price = $row['price'];
$image_name = $row['image_name'];
$featured = $row['featured'];
$active = $row['active'];
?>
<tr>
<td><?php echo $sn++; ?>. </td>
<td><?php echo $title; ?></td>
<td>$<?php echo $price; ?></td>
<td>
<?php
//CHeck whether we have image or not
if($image_name=="")
{
//WE do not have image, DIslpay Error Message
echo "<div class='error'>Image not Added.</div>";
}
else
{
//WE Have Image, Display Image
?>
<img src="<?php echo SITEURL; ?>images/food/<?php echo $image_name; ?>" width="100px">
<?php
}
?>
</td>
<td><?php echo $featured; ?></td>
<td><?php echo $active; ?></td>
<td>
Update Food
Delete Food
</td>
</tr>
<?php
}
}
else
{
//Food not Added in Database
echo "<tr> <td colspan='7' class='error'> Food not Added Yet. </td> </tr>";
}
?>
</table>
</div>
</div>
<?php include('partials/footer.php'); ?>
Attached is a picture of this
What you need is a new column in the table tbl_food
Actual clumns:
//get the values from individual columns
$id = $row['id'];
$title = $row['title'];
$price = $row['price'];
$image_name = $row['image_name'];
$featured = $row['featured'];
$active = $row['active'];
Add a column "owned_by" with the admin_ID of the user that added that food.
Step 1. (that's MySQL, but you can adapt to your DB)
alter table tbl_food add owned_by int;
Step 2.
when some admin add a food, you add this ID value in the insert, with others food information.
Step 3.
When some admin update the food, you check if this food is owned by this admin, and in update query you add
[..]and owned_by = admin_ID;
To accomplish this, you need that any admin has his own ID or email or access token
If all the admins are sharing the same account to upload the food, before of what I said you need to add a multiuser control access system.

How to fetch images from database in base64_encode in php

Thank you all in advance....
I am doing a project in which I have a field to store the image. In that form, the image uploaded is completed with croppie plugin. and I stored the data in base 64 encodings. But I cannot fetch it to a page called view.php but the images are fetched to the form after cropping.
Please help me to figure it out the mistake that I have done
<tbody>
<?php
$no = 1;
$data = mysqli_query($con, "SELECT * FROM `register` WHERE app_registration IS NULL ORDER BY `app_id` DESC ");
while ($row = mysqli_fetch_assoc($data)) {
?>
<tr>
<td><?php echo $row['app_id'] ?></td>
<?php if (!empty($row['image_reference_id'])) {
$data1 = mysqli_query($con, "SELECT * FROM `photo_table` WHERE image_unique_id = '" . $row['image_reference_id'] . "'");
$row1 = mysqli_fetch_assoc($data1)
?>
<td><img src="data:image/jpg;base64,'.base64_encode($row['images']).'"/></td>
<?php } else {
?>
<td><img src="../images/<?php echo $row['app_image'] ?>" style="width: 100px; height: 100px;"></td>
<?php } ?>
<td><?php echo $row['app_name'] ?></td>
<td><?php echo $row['app_mobile_no_1'] ?></td>
</tr>
<?php } ?>
</tbody>
Note: In db the images are in Long Blob
You will need to change the following:
<img src="data:image/jpg;base64,'.base64_encode($row['images']).'" />
to
<img src="data:image/jpg;base64, <?php base64_encode($row['images']);?>" />

How to make images align side by side when fetch multiple images in a single column that belongs to the same category

I am trying to fetch multiple images from a single columns which belongs to the same category and I want this images to be lay side by side with their category. When I fetched the images with their category the category appeared number of times the images.
Take a look at the image below, ABUA appeared once in the user table but has three images in the upload table likewise Eksu which has two images. I do not want the display to be like this, I want the images to align side by side and the details appear once.
My sql query is below:
<?php
//Education
$e = mysqli_query($mysqli, "SELECT * FROM education where fid = '$id' group by schools ");
while($edu = mysqli_fetch_array($e)){
$eid = $edu['fid'];
$sc = $edu['schools'];
$now=mysqli_query($mysqli, "Select distinct * from uploads WHERE fid='$eid' AND category = 'education' and sch='$sc' order by '$sc' ");
while($resultsn=mysqli_fetch_array($now)){
$tempr = explode(',',$resultsn['img_name'] );
foreach($tempr as $imager){
$img = "<img src='../cert/".$imager."' class='img-thumbnail' width='50' height='50'/>";
?>
<tr>
<td><?php echo $img; ?></td>
<td><?php echo $edu['schools']; ?></td>
<td><?php echo $edu['course']; ?></td>
<td><?php echo $edu['qualification']; ?></td>
<td><?php echo $edu['years']; ?></td>
</tr>
<?php
}
}
//}
}
?>
Try this:
while($resultsn=mysqli_fetch_array($now))
{
$tempr = explode(',',$resultsn['img_name'] );
$imgs = '';
foreach($tempr as $imager)
{
$imgs .= "<img src='../cert/".$imager."' class='img-thumbnail' style='display: inline-block;' width='50' height='50'/> ";
}
?>
<tr>
<td><?php echo $imgs; ?></td>
<td><?php echo $edu['schools']; ?></td>
<td><?php echo $edu['course']; ?></td>
<td><?php echo $edu['qualification']; ?></td>
<td><?php echo $edu['years']; ?></td>
</tr>
<?php}?>
You're creating a table row for each one the entries in your second while loop.
If you want the images side by side, you should create the table row inside your first loop and have only image <td> elements added in the second while loop.
After that loop is closed, echo the remaining `' elements inside the initial while loop to display the other fields of your table. You'll have one row with all images for that category instead of multiple rows.
Try this one:
<?php
//Education
$e = mysqli_query($mysqli, "SELECT * FROM education where fid = '$id' group by schools ");
while($edu = mysqli_fetch_array($e))
{
$eid = $edu['fid'];
$sc = $edu['schools'];
$now=mysqli_query($mysqli, "Select group_concat(img_name) as img_name from uploads WHERE fid='$eid' AND category = 'education' and sch='$sc' order by '$sc' ");
while($resultsn=mysqli_fetch_array($now))
{
$tempr = explode(',',$resultsn['img_name'] );
foreach($tempr as $imager){
$imgs += "<img src='../cert/".$imager."' class='img-thumbnail' width='50' height='50' style="margin-right:10px;"/> ";
}
}
?>
<tr>
<td><?php echo $imgs; ?></td>
<td><?php echo $edu['schools']; ?></td>
<td><?php echo $edu['course']; ?></td>
<td><?php echo $edu['qualification']; ?></td>
<td><?php echo $edu['years']; ?></td>
</tr>
<?php
}
?>

upload and display multiple images for one product?

I am working on a basic ecommerce website using PHP/MYSQL. I just need to know how I can upload multiple images for a product and then display them in the products page.
as for uploading multiple images, I don't want to use uploadify or open source codes like that. i rather have 3-4 extra fileupload fields if possible at all!
And I cannot get my head around the displaying the images (multiple images for 1 product). I really don't understand how it should work! so any advice on simple terms would be appreciated.
Currently I can only upload 1 image per product.
Here is what I have so far, please ignore the mysql queries in the first file as this is a not going live yet until I have converted the mysql to mysqli. Just need to get functions sorted first:
upload.php
<?php
// Parse the form data and add inventory item to the system
if (isset($_POST['product_name'])) {
$product_name = mysql_real_escape_string($_POST['product_name']);
$price = mysql_real_escape_string($_POST['price']);
$quantity = mysql_real_escape_string($_POST['quantity']);
$category = mysql_real_escape_string($_POST['category']);
$details = mysql_real_escape_string($_POST['details']);
// See if that product name is an identical match to another product in the system
$sql = mysql_query("SELECT id FROM products WHERE product_name='$product_name' LIMIT 1");
$productMatch = mysql_num_rows($sql); // count the output amount
if ($productMatch > 0) {
echo 'Sorry you tried to place a duplicate "Product Name" into the system, click here';
exit();
}
// Add this product into the database now
$sql = mysql_query("INSERT INTO products (product_name, price, quantity, details, category, date_added)
VALUES('$product_name','$price','$quantity','$details','$category',now())") or die (mysql_error());
$pid = mysql_insert_id();
// Place image in the folder
$newname = "$pid.jpg";
move_uploaded_file( $_FILES['fileField']['tmp_name'], "../inventory_images/$newname");
header("location: add.php");
exit();
}
?>
product.php <<< this is the page that displays the product details and image.
<?php
// Check to see the URL variable is set and that it exists in the database
if (isset($_GET['id'])) {
// Connect to the MySQL database
include "config/connect.php";
$id = preg_replace('#[^0-9]#i', '', $_GET['id']);
// Use this var to check to see if this ID exists, if yes then get the product
// details, if no then exit this script and give message why
$sql = "SELECT * FROM products WHERE id='$id' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
$productCount = mysqli_num_rows($query); // count the output amount
if ($productCount > 0) {
// get all the product details
while($row = mysqli_fetch_array($query, MYSQLI_ASSOC)){
$product_name = $row["product_name"];
$price = $row["price"];
$details = $row["details"];
$quantity = $row["quantity"];
$category = $row["category"];
$date_added = strftime("%b %d, %Y", strtotime($row["date_added"]));
}
} else {
echo "That item does not exist.";
exit();
}
} else {
echo "Data to render this page is missing.";
exit();
}
?>
<table width="900" border="0" cellspacing="0" cellpadding="0">
<tr>
<td width="300" rowspan="5" align="right" valign="top" style="padding-top:10px;"><img src="inventory_images/<?php echo $id; ?>.jpg" width="300" height="450" alt="<?php echo $product_name; ?>" /></td>
<td width="126" height="106"> </td>
<td width="274"><h3 style="font-family:Times New Roman; font-size:1.8em;"><?php echo $product_name; ?></h3></td>
</tr>
<tr>
<td height="120"> </td>
<td><?php echo $details; ?></td>
</tr>
<tr>
<td height="110"> </td>
<td style="font-family:Times New Roman; font-size:1.8em;">Price: £<?php echo $price; ?></td>
</tr>
<tr>
<td height="50"> </td>
<td style="font-family:Times New Roman; font-size:1.8em;">Quantity Left: <?php echo $quantity; ?></td>
</tr>
</table>
Thanks
Well the way you are currently doing it isn't really setup for multiple photos since you aren't storing a reference to the photo in the database. You are simply renaming the image to the primary key of the product. So you will need to either do something like 1_1.jpg 1_2.jpg or you will need to create a database table that stores the filename and the product id so you can have a one to many relationship.
As for uploading more images just add more file inputs to your form.
And for displaying you will need to either pull records from the photo db table or use glob() to find all the files that start with the primary key + '_'.
Also FYI mysql functions should no longer be used as they are deprecated.

How MySql can retrieve and display photos with PHP

I have a PHP site where I have uploaded 10 pictures locally. The pictures are saved in the ./images folder and also resampled to a ./thumbnails folder. I use this query to extract 7 photo file names from the database.
$imgQuery = "SELECT FileName, Title, Description FROM PICTURE WHERE OwnerID='$id' LIMIT 0,7";
The database saves PictureID(PK), OwnerID(UNQ, my id is 2), FileName(stores the file name) and Title for the picture and Description for the picture. I use this method of transferring 7 photo filenames, title and description to an array. But how can I extract them from my ./thumbnails folder and display them on my PHP page?
if($imgResult = mysqli_query($link, $imgQuery))
{
while($imgRow = mysqli_fetch_row($imgResult))
{
$filename[] = $imgRow[0];
$title[] = $imgRow[1];
$description[] = $imgRow[2];
}
}
Here is where I am displaying the thumbnails t1 in the body. I would like to know how can assign the files retrieved by my database to these variables. The description changes based on which name i
$num = count($filename);
while($i < $num)
{
$i = 0;
print <<<photo
<body>
<form action='MyAlbum.php' method='post'>
<table>
<tr><td colspan='7' ><h2 align='center'><?php echo $name;?>'s Album</h2></td>
</tr>
<tr><td colspan='7' ><?php echo $title[$i];?></td>
</tr>
<tr><td colspan='5' ><?php echo $filename[$i]; ?></td><td colspan='2'><?php echo $description[$i];?> </td>
</tr>
<tr>
<td><?php echo $filename[0];?></td> <td><?php echo $filename[1];?></td> <td><?php echo $filename[2];?></td>
<td><?php echo $filename[3]; ?></td><td><?php echo $filename[4]; ?></td> <td><?php echo $filename[5]; ?></td>
<td><?php echo $filename[6]; ?></td>
</tr>
</table>
</form>
$i++;
</body>
</html>
photo;
}
It all depends on two things you don't say: the filename that in full resolution is saved in "FileName", what name has assigned inside thumbnails? And does FileName contain the full path, or only the "bare" file name?
// If
// FileName = "/images/LenaSjooblom.jpg", thumbnail is "./thumbnails/LenaSjooblom.jpg"
// Then
$Thumbnail = './thumbnails/' . basename($FileName);
// If
// FileName = "LenaSjooblom.jpg", thumbnail is "./thumbnails/LenaSjooblom.jpg"
// Then
$Thumbnail = './thumbnails/' . $FileName;
// If
// FileName = "/images/LenaSjooblom.jpg", thumbnail is "./thumbnails/12.jpg"
// Then
$Thumbnail = './thumbnails/' . $PictureID . '.jpg';
The code above you put into the same loop, e.g:
$filename[] = $imgRow[0];
$title[] = $imgRow[1];
$description[] = $imgRow[2];
// ADDED THUMBNAIL - hypothesis 1
$thumbnail[] = "./thumbnails/".basename($imgRow[0]);
and could display with
<img src="$thumbnail[$i]" />
Update
If your thumbnail is the duplicate of filename, then you need nothing else - you can just change the HTML, and add:
<img src="./thumbnails/$filename[$i]" />
and it will instruct the browser to fetch a filename with the same name of the image, but from the thumbnails directory. (If it doesn't work at first, check the path; in a pinch, use an absolute path, such as "/thumbnails/$filename[$i]" ).
You could do
<img src="<?php echo $filePath;?>" alt="some_text">
Just make sure that the variable you have for $filePath is the url to the actual image in the folder

Categories