showint thumbnails issue - php

I am unexperienced in ways of PHP and MySQL, but I am trying to build an image upload website following a tutorial of Kevin Skoglund. Everything was fine up to a point where my images are supposed to show on a page in a html table.
I got everything from my database (image size, type, name, caption), but instead of image thumbnail I get broken link.
Here is relevant html
<tr>
<td><img src="../<?php echo $photo->image_path(); ?>" width="100" /></td>
<td><?php echo $photo->filename; ?></td>
<td><?php echo $photo->caption; ?></td>
<td><?php echo $photo->size_as_text(); ?></td>
<td><?php echo $photo->type; ?></td>
</tr>
Here is php that defines image path
protected $upload_dir="images";
public function image_path() {
return $this->upload_dir.DS.$this->filename;
}
Site root defined:
defined('SITE_ROOT') ? null :
define('SITE_ROOT', DS.'wamp'.DS.'www'.DS.'projekat');
this is folder structure
this is end result
Thanks for taking time to read and help with my problem in advance.

EDIT:
return $photo->image_path() as
projekat/public/images/filename.jpg
and display
<td><img src="/<?php echo $photo->image_path(); ?>"
In html, you can use beginning '/' to indicate root. So if you have stored your relative path in database as
$path = relative/path/to/file
you can use
src = "/<?php echo $path?>"

Related

Codeigniter Display Image With Open Library API

I am retrieving data from my MySQL database, and displaying a table including;
item_id
item_image (empty)
item_title
item_isbn (contains hyphens)
The code I have so far works, in the sense that I am able to retrieve the data and display it in a simple table.
My code so far;
model
class Items_model extends CI_Model {
public function itemList() {
$query = $this->db->query("SELECT * FROM item LIMIT 10");
return $query->result_array();
}
}
view
<table>
<tr>
<td><strong>ID</strong></td>
<td><strong>Image</strong></td>
<td><strong>Title</strong></td>
<td><strong>ISBN</strong></td>
</tr>
<?php foreach ($items as $item): ?>
<tr>
<td><?php echo $item['item_id']; ?></td>
<td><?php echo $item['item_image']; ?></td>
<td><?php echo $item['item_title']; ?></td>
<td><?php echo $item['item_isbn']; ?></td>
</tr>
<?php endforeach; ?>
</table>
controller
class Items extends CI_Controller {
public function index() {
$data['items'] = $this->items_model->itemList();
$this->load->view('item_view', $data);
}
}
I want to use the book's ISBN, retrieve the book cover using Open Library Covers API and populate the image field in the html table.
Apparently this is possible by using the following URL pattern;
http://covers.openlibrary.org/b/isbn/0385472579-S.jpg
I have tried the following code in my view but it doesn't work;
<td><img src="<?php echo ('http://covers.openlibrary.org/b/isbn/'. stripslashes($item['item_isbn']) .'-S.jpg');?>"/></td>
Ideally I would like to display a standard 'No Image Found' jpg, if I'm unable to retrieve an image using Open Library API also, but I'm sure I can work this part out on my own (hopefully!).
Any advice would be appreciated, very new to Codeigniter.
Assuming you have valid ISBN's stored in your database, please change your view to the following:
<table>
<tr>
<td><strong>ID</strong></td>
<td><strong>Image</strong></td>
<td><strong>Title</strong></td>
<td><strong>ISBN</strong></td>
</tr>
<?php foreach ($items as $item): ?>
<tr>
<td><?php echo $item['item_id']; ?></td>
<td><img src="http://covers.openlibrary.org/b/isbn/<?php echo $item['item_isbn']; ?>-S.jpg" /></td>
<td><?php echo $item['item_title']; ?></td>
<td><?php echo $item['item_isbn']; ?></td>
</tr>
<?php endforeach; ?>
</table>
If an image is not found, a 1px by 1px transparent pixel is displayed.
So the code syntax to display the image is:
<img src="http://covers.openlibrary.org/b/isbn/<?php echo $item['item_isbn']; ?>-S.jpg" />
Resulting screenshot from my test
Update (If No Image Found)
As per the documentation:
By default it returns a blank image if the cover cannot be found. If
you append ?default=false to the end of the URL, then it returns a 404
instead.
To add your own fallback image, you could append this parameter to the image URL, and then check if the file doesn't exist.
There are multiple ways to check if a file exists or not. Using curl would probably be the most graceful but here is a...
Quick & Dirty Method
This uses a ternary operator in conjunction with the getimagesize function to handle the fallback. You will need to ensure that GD (image processing library) support is enabled in your version of PHP for this.
<img src="<?php echo (!getimagesize('http://covers.openlibrary.org/b/isbn/' . $item['item_isbn'] . '-S.jpg?default=false')) ? '/path/to/your-image.jpg' : 'http://covers.openlibrary.org/b/isbn/' . $item['item_isbn'] . '-S.jpg'; ?>" />
Think of the ternary operator syntax like an inline if/else statement.

How do I reference an image path to my PHP File?

I am a student and I have been given a project to do, we made a database in MySql called Video_Game_Shop. Then we had to connect it to a website using PHP and HTML. And we have to show on one page all the games in our database listed. So we did that by calling a procedure which ordered the games by price. This is where I have the problem. We now need to show images for every one of these games on the page. What I have done so far I have downloaded the pictures, for every game we have listed, and I have no idea on how to do that task. I heard of some ways of inputting the path for the images or to use BLOB file type, but I don't know how to do any of that. I will add the PHP file so you can more easily understand my situation. I would be very grateful if you could help me. :)
<!DOCTYPE html>
<html>
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css"/>
<style>
h1 {font-family:Serif; font-size:22px; text-align:center}
p {font-family:Serif; font-size:16px}
.container {
width: 100%;
clear: both;
opacity: 1
}
input[type=number] {
border:2px #ffo;
opacity:0.2}
input[type=text] {
border:2px #ff0;
opacity:0.2}
input[type=date] {
border:2px #ff0;
opacity:0.2}
</style>
<h1>videogames</h1>
<head>
<title>videogames</title>
<link rel="stylesheet" href="css/table.css" type="text/css" />
</head>
<body background="http://i.imgur.com/yGkEuwZ.jpg">
<?php
require_once 'user.php';
try {
$conn = new PDO("mysql:host=$host;dbname=$dbname",
$username, $password);
// execute the stored procedure
$sql = 'CALL List_game_by_price()';
$q = $conn->query($sql);
$q->setFetchMode(PDO::FETCH_ASSOC);
} catch (PDOException $pe) {
die("Error occurred:" . $pe->getMessage());
}
?>
<div class="container">
<table border="1" align="center" width="90%">
<tr>
<th>GameID</th>
<th>Name/th>
<th>Developer</th>
<th>Publisher</th>
<th>ESRB</th>
<th>Relase Date</th>
<th>Platform</th>
<th>Genre</th>
<th>Language</th>
<th>Price</th>
</tr>
<?php while ($r = $q->fetch()): ?>
<tr>
<td><?php echo $r['GameID'] ?></td>
<td><?php echo $r['Name'] ?> </td>
<td><?php echo $r['Developer'] ?></td>
<td><?php echo $r['Publisher']?></td>
<td><?php echo $r['ESRB'] ?></td>
<td><?php echo date_format ($r['Relase Date']) ?></td>
<td><?php echo $r['Platform'] ?></td>
<td><?php echo $r['Genre'] ?></td>
<td><?php echo $r ['Language'] ?></td>
<td><?php echo $r['Price'] ?></td>
</td>
</tr>
<?php endwhile; ?>
</table>
</div>
</body>
</html>
A quick solution without changing your database at all would be to upload images to the FTP and rename them for their name to match the GameID.
Example: Change your Mass-Effect2_600x400.jpg into 1.jpg.
In your fetch (where you show the data from the base) just add another something like this
<td><?php echo '<img src="path/to/'.$r['GameID'].'.jpg" />' ?></td>
You could create an assets table with cols [ID Primary Key], [Url]. Create a foreign key on your products table AssetID. This way you only have one record per image URL, and multiple products can use that image.
Upload the files to FTP and insert records into the assets table.
If you really wanted to go above and beyond your task, you could create an image upload for the products from an Admin panel. Which when uploaded inserts the path into the assets table and assigns the AssetID to the product.
Upload the images to an ftp, input your image names in a column and then call that in your query. Might be a bit of a workaround but it works well!
<td><img src="path/to/<?= $r['GameID'] ?>.jpg" /></td>

Retrieving images from the path data saved at SQL database

Part of my code to retrieve the stores images and the content from the SQL database (only the path is saved at the database) is as follows. I get the content displayed except the images.
My database record says the path as; C:/xampp/htdocs/bro/productLoader/uploaded_files/1377935517-IMG_0150.JPG
The image source I entered does not seems to be helping me. How do I adjust my approach to make sure the pictures are extracted from the database?
code as follows;
<?php
$j=0;
while ($rows = mysql_fetch_assoc($query))
{
?>
<tr style="height:100px; font-family: Georgia, 'Times New Roman', Times, serif;">
<td style=" width:100px;">
<img src='<?php $rows['pictures'];?>'><br><br>
</td>
<td style="text-align:justify;"><?php echo $rows['description'];?><br><br></td>
<td style="text-align:right;"><?php echo $rows['brand'];?><br><br></td>
<td style="text-align:right;"><?php echo $rows['model'];?><br><br></td>
<td style="text-align:right;"><?php echo $rows['unitprice'];?><br><br></td>
<td style="text-align:right;"><?php echo $rows['availability'];?> units available<br><br></td>
<td><input type='submit' id='buynow[]' class='buynow' name='but' value='Buy'><br><br></td>
</tr>
<?php
$j++;
}
echo "</table>";
}?>
You have to insert only relative path excluding your document root. That is if your document root is set till htdocs folder only (which is default in apache for localhost) then you have to insert image path from this document root in your case
/bro/productLoader/uploaded_files/1377935517-IMG_0150.JPG
And yes you need to echo that variable too.
Try html link first
<img src='bro/productLoader/uploaded_files/1377935517-IMG_0150.JPG' />
Ok
Try this fixed:<img src='<?php echo substr_replace($rows['pictures'], '',0, 16);?>'/>

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

Use output from MySQL to extract additional info

How can I use the output of a MySQL query as to extract extra info from the database about that output?
For example, if my query generates a list of names and there is extra info about each name existing in the database, when I click on the name on the output page, the system will extract the relevant info from the database and show it on another page.
EDIT: Here's the code:
<?php
// you can delete mysql-assoc
while($row = mysql_fetch_array($rs, MYSQL_ASSOC)) {
?>
<tr align="center">
<td width="5%">
<a href="// I don't know what do put here " >
<?php print("{$row["pid"]}");?>
</a>
</td>
<td><?php print("{$row["place"]}");?></td>
<td><?php print("{$row["date"]}");?></td>
<td><?php print("{$row["ppp"]}");?></td>
<td><input type="button" value="Book"></td>
</tr> <?php } ?>
Set each row of the first output results equal to a variable, and then have an if statement in php that looks for strings in those variables, and then (upon some sort of a page refresh button since php is server-side code) displays the additional content.
Great; here's what you're missing:
<a href="<?php // I don't know what to put here ?>" >
Should be:
<a href="<?php echo 'database.php?action=viewrecord({$row["pid"]})'?>" >
From there, you should be able to extract the relevant info using the pid of the user.
On a side note, unless you're really worried about spacing, you should just dump out the relevant HTML; doing so will save you the task of repeatedly typing <?php ?> every time you want to dump out a variable.
<?php
// you can delete mysql-assoc
while($row = mysql_fetch_array($rs, MYSQL_ASSOC)) {
echo "<tr align='center'>";
echo "<td width='5%'>";
echo "<a href='database.php?action=viewrecord({$row['pid']})'>";
echo "{$row['pid']}";
echo "</a>";
echo "</td>";
echo "<td>{$row['place']}</td>";
echo "<td>{$row['date']}</td>";
echo "<td>{$row['ppp']}</td>";
echo "<td><input type='button' value='Book'></td>";
echo "</tr>";
}
?>
Thanks for the help but this doesn't work :( I'm beginner in php when I press the record the url looks like localhost/ass/database.php?action=viewrecord%28{$row[
This isnt a direct answer to your question perse but since youre new to php im goign to through it out there. The syntax you uisng makes unicorns cry. It give me a headache jsut tryign to decipher it. Heres the same code in an alternative way:
<?php while($row = mysql_fetch_array($rs, MYSQL_ASSOC)): ?>
<tr align="center">
<td><?php printf('%s', url_encode('viewrecord('.$row['pid'].')'), $row['pid']); ?></td>
<td><?php echo $row['place']; ?></td>
<td><?php echo $row['date']; ?></td>
<td><?php echo $row['ppp']; ?></td>
<td><input type="button" value="Book"></td>
</tr>
<?php endwhile; ?>
However this database.php?action=viewrecord() worries me. I hope youre not using eval to execute a function passed by URL. Typically this would look something more like: database.php?action=viewrecord&id=2. You would verify that the action parameter is valid, and then invoke a function tied to that parameter which may or may not be the actual function name, and you would pass in the id parameter.
Eaxample database.php:
$action = isset($_POST['action']) ? $_POST['action'] : 'index';
switch($action) {
case 'viewrecord':
if(isset($_POST['id']) {
viewrecord((integer) $_POST['id']);
}
break;
// a whole bunch of other cases here for other actions
default:
// the default thing to do if an action is in valid
}
// the rest of your processing

Categories