PHP/HTML/mySQL URL Caching Problem - php

I have this function: http://pastebin.ca/2058418
It basically checks to see if a tables contains some URLs to pictures of a band. If it does, then it will order the table by random, choose the first result and then output the html code to insert the picture. If the table does not have the pictures of that specific band, then it downloads an XML file which contains the image URL's, parses the XML and inserts in into the table, and then gets the HTML code for the image like before.
In terms out html output, you can't tell if the image URL has been cached or not. HOWEVER, when the image URL is cached (for the first time), whatever web browser you use will not display the image. The HTML is fine - the image is linked correctly.
Do you have any ideas? A live version of the site which contains this function is here: http://redfern.me/similar/. I have just emptied the tables, so there shouldn't be many cached URL's. Try choosing a band, and then see if the image loads. You can tell if the URL's where cached or not by looking at the bottom of the page.

basically looks like you wasn't returning after you fetched the image first time.
<?php function getimage($artist){
$api_key = "XXXXXXXXX";
$iquery = mysql_query("SELECT url FROM `images` WHERE artist = '".$artist."' ORDER BY RAND() LIMIT 1");
if($artist != ""){
$artist = str_replace(" ", "+", $artist);
if(mysql_num_rows($iquery) == 0){
$url = "http://developer.echonest.com/api/v4/artist/images?format=xml&api_key=".$api_key."&name=".$artist."&results=20";
$data = file_get_contents($url);
if($data=false){return 'Error Getting Image';}
$images = new SimpleXMLElement($data);
foreach($images as $image){
foreach($image->image as $indimage){
$insiquery = "INSERT INTO images (id, artist, url) VALUES (NULL, '$artist','".$indimage->url."')";
mysql_query($insiquery);
}
}
return "<img src=\"".$indimage->url."\" alt=\"$artist image\" />";
}else{
$imgurl = mysql_fetch_array($iquery);
return"<img src=\"".$imgurl['url']."\" alt=\"$artist image\" />";
}
}
else{
return"Image Aquire Function Error: <i>No Band Specified</i>";
}
return null;
}?>
echo getimage('Britney Spears');

That's simply because when you enter to the "xml call" your var "$imgurl[0]"
is empty :
try something like this :
$images = new SimpleXMLElement($data);
$xmlImgUrl = array();
foreach($images as $image){
foreach($image->image as $indimage){
$xmlImgUrl[] = $indimage->url;
$insiquery = "INSERT INTO images (id, artist, url) VALUES (NULL, '$artist','".$indimage->url."')";
mysql_query($insiquery);
}
}
}
$imgurl = $nrows == 0 ? $xmlImgUrl : mysql_fetch_row($iquery);
if(!empty($imgurl)) echo "<img src=\"".$imgurl[0]."\" alt=\"$artist image\">";
which instantiate an array of image urls when no results in mysql.

Related

enter information into database of an input array....its always inserting the last $_POST value

I have a input file to select some pdfs and after I select pdfs some text inputs open so I can give a title for each pdf.
So, I have a text input like this:
<input type="text" name="title[]" value=""/>
And then I verify if user fill these inputs like this:
if(isset($_POST['sendForm'])){
foreach ($_POST['title'] as $title) {
if(empty($title)){
echo 'Please give a title';
$ok = false;
}
If user fill all titles of each pdf, I want to upload my pdfs to my folder and insert in database information about uploaded pdfs, and I also want to save in database title of each pdf.
The problem Im having is that IF I upload two pdfs and give to my first pdf title of "test1" and to my second "test2" name, on my database these two pdfs titles are saved with same title, that is always title of my last title pdf, in this case "test".
Im using this code below for this example, do you see what can be wrong here?
if($ok){
if(!empty($_FILES['pdfs']['tmp_name'])){
$pdfs = $_FILES['pdfs'];
$countPdf = count($_FILES['pdfs']['tmp_name']);
$folder = '../../uploads/pdfs_articles/';
for($i=0;$i<$countPdf;$i++){
$ext = substr($pdfs['name'][$i],-3);
$pdfName = $idlast.'-'.$i.time().'.'.$ext;
if($pdfs['type'][$i] == 'application/pdf'){
//here I want to get all values of my inputs with name title[]
// so I can insert on database title of each pdf
foreach ($_POST['title'] as $title) {
$pdf_title = $title;
}
$insPdf = $pdo->prepare("INSERT INTO pdfs_articles (pdf, article_id, title) VALUES (?,?,?)");
$insPdf->bindParam(1,$pdfName);
$insPdf->bindParam(2,$idlast);
$insPdf->bindParam(3,$pdf_title);
$insPdf->execute();
move_uploaded_file($pdfs['tmp_name'][$i], $path.$pdfName);
}
}
}
}
You are looping through all of your titles leaving $pdf_title with the last value. Then you are actually handling your uploaded PDFs.
Get rid of that loop and access the $_POST['title'] array just like you do your uploaded files:
$insPdf = $pdo->prepare("INSERT INTO pdfs_articles (pdf, article_id, title) VALUES (?,?,?)");
$insPdf->bindParam(1,$pdfName);
$insPdf->bindParam(2,$idlast);
$insPdf->bindParam(3,$_POST['title'][$i]);
$insPdf->execute();
move_uploaded_file($pdfs['tmp_name'][$i], $path.$pdfName);
I think you need to replace this:
foreach ($_POST['title'] as $title) {
$pdf_title = $title;
}
With this:
$pdf_title = $_POST['title'][$i];

Displaying Correct IDs for Items (for example images)[',1,2,3,']

I need to display Correct IDs for Items images.
I have two tables. One containing the id, title, text and image.
The first section references are correct:
<?php
$st = $dbh->query("SELECT * FROM `info` ");
$st->execute(array($_GET['media']));
foreach ($st as $post):
$title = $post['title'];
$image = $post['image'];
$id = $post['id']; ... ->
Where the result of the image is: example ,1, (LIKE as ',?,' etc)
Distal part of the code retrieves the image data in the second table, but not correctly according to the first reference.
$pi = $post['image'];
$statementUser = $dbh->prepare("SELECT source FROM media WHERE id LIKE ? ");
$statementUser->execute(array($pi));
$name=$statementUser->fetchColumn(0);
$path = $settings['cms']['media_path'];
# Presentation part:
echo "<img src='$name' />";
endforeach;
?>
According to these, database displays the picture, but as incorrect.
Can anyone help me to fix this issue?
Solution: We need, get a readable string.
Example Function:
function clean_item_str($string){
return preg_replace('/[^a-zA-Z0-9_]/', '', $string);
}

Comparing a php variable and mysql table element that has backslashes

I'm trying to create an online database of the music I locally have on my computer. I already have a table of every song in my library and would like to create a different table with just the song ID's (auto-incremented when I added the songs to my main table) that act as one of my playlists.
From what I can tell, the only 100% certifiable method for matching the songs is by the location on my disk ( C:\Users\username\Music\iTunes\iTunes Media\Music\Jonathan Coulton and GLaDOS\Portal\128 128 Still Alive Duet.mp3 ) as an example. In my PHP code I get the song location into a variable and if I print it relative to the equivalent song location in my MYSql table, they match up exactly but when I try to run a select statement using that, it gives me an error. From what I can tell this is being caused by the backslashes in the location info.
This is the select statement I'm using,
SELECT id FROM itunes WHERE Location=$locationval
where $locationval is the current song's location, id is the autoincremented id in my main table, and itunes is my main table.
Is there any way around this? And as I am a beginner, is the backslashes really the issue?
For reference here is the full code for importing the playlist, its using the DB plugin for PEAR (a PHP extension).
<?php
// define table name
define('TABLE_NAME', 'playlist');
// create database connection
require_once('DB.php');
$dsn = 'mysql://username:password#localhost/itunes';
$DB =& DB::connect($dsn);
if (DB::isError($DB)) {
die($DB->getMessage());
}
$DB->setFetchMode(DB_FETCHMODE_ASSOC);
// load text file
$file = file_get_contents('Portal.txt');
// explode on new line
$file = explode("\r", $file);
set_time_limit(0);
// loop through each line in the file
foreach ($file as $key => $value) {
// explode on tab to get column list
$exploded = explode("\t", $value);
// check for first row, which contains column headers
if ($key == 0) {
}
else{
if(count($exploded)>3)
{
$locationval=$exploded[26];
echo $exploded[26];
echo "<br />";
$result = mysql_query("SELECT id FROM itunes WHERE Location=$locationval");
//$result = mysql_query("SELECT * FROM itunes WHERE id=8292");
set_time_limit(0);
$row = mysql_fetch_row($result);
//test statements to see if the query worked
echo "Test: ";
echo $row['id'];
echo $row['Location'];
echo "<br />";
}
}
}
?>
Which was modified from the code here: http://ericlondon.com/posts/208-exporting-itunes-data-into-mysql-and-creating-sql-to-show-top-rated-albums
If any more info is needed, please let me know.
You need to escape the backslashes when using it in mysql as a string literal, so just replace your following line:
$result = mysql_query("SELECT id FROM itunes WHERE Location=$locationval");
for this one:
$result = mysql_query("SELECT id FROM itunes WHERE Location='". str_replace('\\','\\\\',$locationval) . "'");
that should do what you want.

Delete files that are not in my database

I'm trying to delete photos from a folder, which is called, "photos", that are NOT currently in my database. (These are all photos that have stacked up as I've been building the website and testing it and such, so now it's time to take the site live and I don't want all this waste in it)
I have three tables with photo information in them, and a number of columns throughout. Below is a mockup query of about what I THINK it should look like.
SELECT left_image, right_image, photo1, photo2, photo3, photo4, home_photo
FROM about_photos, facilities, home
left_image and right_image go with about_photos.
photo1, photo2, photo3 and photo4 go with facilities.
home_photo goes with home.
Also, I need to use a wildcard for the end of the photo, because the files have thumbnails, so for instance the original photo would be called, abcimage.jpg but there would be abcimage.jpg, abcimage_medium.jpg, abcimage_thumb.jpg also in the database I only store, photos/abcimage and add the rest of the filename depending on where it goes.
$directory = "../path/to/photos_directory/";
//get all image files with a .jpg extension.
$images = glob($directory . "*.jpg");
foreach($images as $image)
{
$name = explode('_',$image);
$name = 'photos/' . $name[0];
$sql = mysql_query("SELECT id FROM table WHERE photo1='$name' OR photo2='$name'");
if(mysql_num_rows($sql) == 0)
unlink($directory . $image);
}
You have two options:
One:
With an SQL query, get a complete list of all the photos referenced in your database
iterate through the files in your directory
if the file is an image AND it is not in your list, delete the file.
Two:
iterate through the files in your directory
if the file is an image
query the database for that filename
if the response is empty, delete the file
The exact SQL query depends on your table structure, which you have not provided.
The best option depends mostly on scale. If there are lots of images in the database, then the first option involves having a very large list in memory. However the second version involves many more database queries. So it's a tradeoff.
There are more sophisticated options involving caching and pre-emptive queries, but I imagine you don't want to go that deep yet.
Something like the following. I've also got original files in the folder and I limit to 500 deletions at a time. Tweak as you need. Hope it saves somebody time...
<?php
require 'session.php';
require 'settings.php';
/* Execute the query. */
$DBH = new PDO($mssql_driver.'='.$mssql_server.';'.$mssql_dbkey.'='.$mssql_database, $mssql_username, $mssql_password);
$DBH->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$tsql = 'select * from ProductImage';
$PRE = $DBH->prepare($tsql);
$PRE->execute();
$pictures =$PRE->fetchAll(PDO::FETCH_ASSOC);
$directory = $_SERVER["DOCUMENT_ROOT"]."\..\..\products\pictures/";
//get all image files with a .jpg extension.
$images = glob($directory . "*.jpg");
$counter =0;
foreach($images as $image)
{
$name = explode('pictures/',$image);
$name = $name[1];
$foundImage = false;
print "checking: ".$name;
foreach ($pictures as $picture){
$original_file = explode('.', $picture['Image_Big']);
$original_file = $original_file[0].'-original.'.$original_file[1];
if ( ($picture['Image_Small'] == $name)|| ($picture['Image_Big'] == $name) || ( $original_file == $name) || ($picture['Image_Thumb'] == $name) || ($picture['Image_PriceList'] == $name)){
$foundImage = true;
break;
}
}
if (!$foundImage) {
unlink($directory . $name);
print "....deleting";
$counter += 1;
}
print "<br />";
if ($counter> 500){
exit;
}
}
?>

Storing affiliate image inside my database

This is a basic code which I use to pull info from my affiliate product feed. I'm pulling, as you will see below, picture links...and store the urls into my databse. The problem is that I'm showing 20 products per page, and if the affiliate serves isn;'t working properly it slows donw my sites alot.
What i'd like to do is store the whole iamges somehow and hot the urls... I think that will improve my sites performance alot. Any ideeas?
$feed = 'my affiliate feed';
$xml = simplexml_load_file($feed);
foreach( $xml->productinfo as $productinfo )
{
$pic0 = $productinfo->picture[0];
$pic1 = $productinfo->picture[1];
$pic2 = $productinfo->picture[2];
mysql_query("INSERT INTO ".$table." (pic0, pic1, pic2) VALUES ('$pic0', '$pic1', '$pic2')");
}
Thank you
First change pic0, pic1 and pic2 fields to BLOB type. (You might also want to store the MIME type with getimagesize() for use with header() when delivering the images.)
$feed = 'my affiliate feed';
$xml = simplexml_load_file($feed);
foreach( $xml->productinfo as $productinfo )
{
for($i = 0; $i<=2; $i++) {
$pic[$i] = mysql_real_escape_string(file_get_contents($productinfo->picture[$i]));
}
mysql_query("INSERT INTO $table (pic0, pic1, pic2) VALUES ('$pic[0]', '$pic[1]', '$pic[2]')");
}
I presume that you have an ID field in $table. Deliver images in a new PHP script like this:
if (!isset($_GET['id'])) die('No ID');
if (!isset($_GET['pic']) || !in_array($_GET['pic'], array(0, 1, 2)))
$i='0';
else
$i=mysql_real_escape_string($_GET['pic']);
$sql = sprintf( "SELECT pic$i FROM $table WHERE id=%s", mysql_real_escape_string($_GET['id']));
$result = mysql_query($sql) or die("Invalid query: " . mysql_error());
$row=mysql_fetch_array($result);
header("Content-type: image/jpeg");
echo $row[0];
well you can also store it as base64
blobs make the website not faster, the more db requests you have the more slow is the website
if that are just a few images its ok and if you have a fast db server

Categories