Codeigniter Display Image With Open Library API - php

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.

Related

how to transfer value to another page with link?

Hello i'm stil learning, using Codeigniter can someone tell me, or give example code?
what i need is in Round Id we have 111 i want give it link and search database with value 111 how to do that? here the code i tried but still not right
<div class="row" id="ajaxdata">
<table border="1">
<tr>
<th>Round Id</th>
<th>Player Id</th>
<th>Bet Place</th>
<th>Total Bet</th>
<th>Win</th>
<th>Lose</th>
</tr>
<?php foreach ($tbl_bet_spot as $data) {?>
<tr>
<td><?php echo $data->round_id;?>
<td><?php echo $data->id;?></td>
<td><?php echo $data->bet;?></td>
<td><?php echo $data->total_bet;?></td>
<td><?php echo $data->win;?></td>
<td><?php echo $data->lose;?></td>
</tr>
<?php } ?>
</table>
</table>
</div>
controller
public function detail_round_id(){
$select = $_GET['select'];
$data['tbl_bet_spot'] = $this->login_model->selectRoundId_by_round($select)->result();
print_r ($data);
}
i just try with my code and it work now, but it's static in here
<td><?php echo $data->round_id;?>
how i can send this value <?php echo $data->round_id;?> properly into controller? thanks a lot.
Use this code
<td><?php echo $data->round_id;?></td>
controller
public function detail_round_id(){
$select = $this->uri->segment(3);
$data['tbl_bet_spot'] = $this->login_model->selectRoundId_by_round($select)->result();
print_r ($data);
}
Try this may help you,
In view make link like this,
<td><?php echo $data->round_id;?>
And in controller add parameter like this,
public function detail_round_id($id){
$data['tbl_bet_spot'] = $this->login_model->selectRoundId_by_round($id)->result();
print_r ($data);
}
view page you pass value like this
<?php echo $data->round_id;?>
In controller get value like this
$select=$this->uri->segment(4);
hope this will help

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>

showint thumbnails issue

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?>"

jquery how to get value in a table

I have the following code that generates a table:
<table class="table table-bordered table-striped" id="assignedvs">
<thead>
<tr>
<th>VlId</th>
<th>Name</th>
<th>Status</th>
<th>Voice</th>
<th>Jumbo</th>
<th>Mode</th>
</tr>
</thead>
<tbody>
<?php foreach ($vln as $vlndetail): ?>
<tr>
<td id='vlid'><?php echo $vlndetail['VlId'] ?></td>
<td><?php echo $vlndetail['Name'] ?></td>
<td><?php echo $vlndetail['Status'] ?></td>
<td><?php echo $vlndetail['Voice'] ?></td>
<td><?php echo $vlndetail['Jumbo'] ?></td>
<td><?php echo $vlandetail['Mode'] ?></td>
</tr>
<?php endforeach ?>
I need to find the row where the VlId matches what the user has specified in a text box. Once I've found this record, I want to grab value in the mode column for the particular row.
here's what i've written so far:
$('#delete').live('click', function() {
//get a count of all records. only allowed to delete if you have more than one + the header.
var reccount = $('#assignedvs tr').length;
if (reccount > 2)
{
//loop through the table
$('#assignedvs tr').each(function() {
var temp = $(this).find(".vlid").html();
console.log(temp);
if (temp == $('#uservalue').val){
//grab mode column
}
});
}
else
{
alert("error: must have at least 1 record.");
}
});
problem - the code i have to reference the vlid column is incorrect. it always prints a null to the console.
Can you tell me what I've done wrong?
thanks.
EDIT 1
I changed my id to a class and changed my jquery back to the original code I had. it's working - except for the fact that I think it's including the header . I have 4 rows + header. When i check the console results, the first print out is always NULL and then the correct value for the 4 records. how do it get it to ignore the header?
That's because you are finding by className, not by id. To find by id, use the following instead:
$(this).find("#vlid").html();
However, since ids should be unique across the entire document, a better solution would be to maintain your current code, and instead of using <td id='vlid'>, use <td class='vlid'>.
Also note that val() is a function. Thus, to get the value of a given input, you should use $('#uservalue').val().
EDIT: To exclude the header, use the $('#assignedvs tbody tr') selector. This way, you only get rows that are descendants of tbody, thus ignoring the header rows, which descend from thead.
couple of changes:
<?php echo $vlndetail['VlId']; //missing semi-colon ?>
var temp = $(this).find("#vlid").html(); vlid is an id
You can easily do this via datatables at http://datatables.net
var temp = $(this).find("#vlid").html(); // .vlid (by class) changed to #vlid (by id)
An even easier solution.
Assign an ID to each row with the vlId (possibly prepend tr_ to the ID to avoid duplication).
Assign a class with the column name to each datacell.
Like so:
<?php foreach ($vln as $vlndetail): ?>
<tr id='tr_<?php echo $vlndetail['VlId'] // set the ID ?>'>
<td class='vlid'><?php echo $vlndetail['VlId'] ?></td>
<td class='Name'><?php echo $vlndetail['Name'] ?></td>
<td class='Status'><?php echo $vlndetail['Status'] ?></td>
<td class='Voice'><?php echo $vlndetail['Voice'] ?></td>
<td class='Jumbo'><?php echo $vlndetail['Jumbo'] ?></td>
<td class='Mode'><?php echo $vlandetail['Mode'] ?></td>
</tr>
<?php endforeach ?>
Then to get the Name of the selected vlID just do this JQUERY:
var rowID = "#tr_" + $('#uservalue').val(); // this is optional. I prefer to cache values for increased code readability.
$(rowID + " td.Mode").dostuffhere(); // this selector returns the Mode cell for the row indicated by the user
This will grab the Mode column of that specific row.

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