Recent Topics

1 Feb 12, 2005 18:21    

I've got an idea to have a random picture that's linked to it's related blog entry, so you could click the picture and then read the story behind the picture ...

EDIT: Cut-n-paste code & detailed instructions for a "random picture linked to a blog entry" can be found
......
[url=http://www.randsco.com/index.php/2005/03/06/random_picture]HERE[/url]

A couple of assumptions: (1) pics are included with blog entries (2) pics are in a single directory & named with a date & (3) few blog entries per day (as what I'm thinking would be to call ALL blogs from a particular day).

A random pic is a nifty idea and there seem to be several ways of doing it. I found this nice code at http://photomatt.net/scripts/randomimage by Matt Mullenweg.

<?php
/*
    By Matt Mullenweg > http://photomatt.net
    Inspired by Dan Benjamin > http://hiveware.com/imagerotator.php
    Latest version always at:
    http://photomatt.net/scripts/randomimage
*/

// Make this the relative path to the images, like "../img" or "random/images/".
// If the images are in the same directory, leave it blank.
$folder = '';

// Space seperated list of extensions, you probably won't have to change this.
$exts = 'jpg jpeg png gif';

$files = array(); $i = -1; // Initialize some variables
if ('' == $folder) $folder = './';
$handle = opendir($folder);
$exts = explode(' ', $exts);
while (false !== ($file = readdir($handle))) {
    foreach($exts as $ext) { // for each extension check the extension
        if (preg_match('/\.'.$ext.'$/i', $file, $test)) { // faster than ereg, case insensitive
            $files[] = $file; // it's good
            ++$i;
            }
        }
    }
closedir($handle); // We're not using it anymore
mt_srand((double)microtime()*1000000); // seed for PHP < 4.2
$rand = mt_rand(0, $i); // $i was incremented as we went along

header('Location: '.$folder.$files[$rand]); // Voila!
?>

So much for the random image part.

How to link it to the entry? Well, I'm thinking that image filenames could include the date, of the format: 050214-myPic.jpg (i.e. Feb 14 2005) By adding the date, it seems that one could extract the 'date' using PHP and then make the random picture link using the "m" URL parameter.

something like:

<a href="www.mysite.com/blog/stub.php?m<?php $date ?>" title="click photo get the story behind the picture"><img src="../../photos/randomPhoto.php" alt="random pic" title="" /></a>

Problem? I don't know SQUAT about PHP programming. How difficult would it be to extract the date from the random pic fileneme?

If someone could point me in the right direction:
[list]

  • Let me know how "doable" my idea is ... or

  • If it's simple, add the code to Matt's script in the form of a global variable ... or

  • point me to a good, online resource to start learning PHP!

  • [/list:u]

    Thanks. Any help is greatly appreciated.

    2 Feb 12, 2005 22:46

    Whew! I finally got Matt's code integrated with my _main.php file.

    First, I got his code working externally. Easy. Just like he describes on his site: Put the code in a 'rotate.php' file in the picture directory (wherever that happens to be). Then simply place

    <img src="../relativePathTo/rotate.php" alt="alt" style="width:150px; height:250px;" />

    into your _main.php file. Boom, you now have a random image placed on your page.

    Next, I wanted to get his code into my _main.php file. Don't ask me why, maybe just because I think it's more organized?

    Tough going for a non-PHP guy! I have NO IDEA what that header statement does to pass the file location to the IMG call, and for the life of me, I couldn't get his original (supposedly relative) "$folder" variable to work properly. I ended up simply hard-coding everything in, creating a directory in MySkin folder called "pics", just to keep things simple. (Now that it's working, I can change it to whatever I want).

    Here's the final:

    <?php
    /*
    By Matt Mullenweg > http://photomatt.net
    Inspired by Dan Benjamin > http://hiveware.com/imagerotator.php
    Latest version always at: http://photomatt.net/scripts/randomimage
    This Vers, modded by stk http://randsco.com for _main.php file ( b2evolution.net )
    */
    
    $fileExts = 'jpg jpeg png gif';
    
    $picFiles = array(); $i = -1; // Initialize some variables
    $folderLoc = opendir('/home/mysite/blogs/skins/mySkin/pics');
    $fileExts = explode(' ', $fileExts);
    
    while (false !== ($picFile = readdir($folderLoc))) {
    foreach($fileExts as $fileExt) { // for each Ext check the Ext
    if (preg_match('/\.'.$fileExt.'$/i', $picFile, $extTest)) { // faster than ereg, case insensitive
    $picFiles[] = $picFile; // it's good
    ++$i; } } }
    
    closedir($folderLoc); // We're not using it anymore
    mt_srand((double)microtime()*1000000); // seed for PHP < 4.2
    $randNum = mt_rand(0, $i); // $i was incremented as we went along
    
    $randPic = './pics/'.$picFiles[$randNum];
    echo '<img src="'.$randPic.'" alt="test" style="width:150px" />';
    
    ?>  

    This will work for anyone wanting a random image, pulled from a specific directory. You just need to change the "opendir" location (don't know if relative paths can be used. I just used the fully qualified path, to avoid probs). You also need to change the "$final" variable path (here I used a relative path, referenced from "MySkin" folder, where _main.php is located).

    Now, I just need some help extracting with string variables, so I can extract the date from '$lbafiles[$lbarand]' & put it into a <a> tag and link it to the journal entry.

    Any helpers?

    3 Feb 13, 2005 00:42

    Is that not like using a sledge hammer to crack a nut ?

    Why don't you just search evo_posts for post_content like '%<img%' (think that's the right sql)

    That'd give you all posts with images, just choose a random one, put the image on page and a link to the original post.

    ?

    4 Feb 13, 2005 04:19

    ?????

    You opened the door, I'm walking through, but it's still pretty bloody dark in here!

    Sometimes you're stuck using the tools you have. I've got a sledgehammer, I guess, and I'm missing all those jewelers tools you've got ;)

    (Did I say I'm a PHP/mySql zero?) :oops:

    I really like what you're proposing, because it means that I don't have to change my current image subdirectory file structure and file naming conventions, but I haven't a clue on how to get started.

    It does make sense to query the DB ... it's there, open, has all the info, but that's some serious querying. I've played around with the idea a bit, using the LIKE %"<img"% you suggested. I could prolly do a pick at random (think I remember seeing that one), but how to get the image extracted. Seems like a complicated query ... like getting the length between <img and /> & then extracting the full image tag?

    What a way to learn mySQL! Yowza ... my head hurts. :lol:

    5 Feb 13, 2005 12:19

    Ok, this may not be the prettiest of code (lol, my php/mySql knowledge is about 1/2 of yours :p), but it works :-

    
    <?php
    
    // get the last post ID
    $randomMax=$DB->get_row('select ID from T_posts order by ID desc limit 0,1');
    
    // keep asking for a random record till we get one with an img tag
    do{
    $randomRecord=mt_rand(0,$randomMax->ID);
    $randomSql="select ID,post_content from T_posts where post_content like '%<img%' and id > '$randomRecord' limit 0,1";
    $randomChoice=$DB->get_row($randomSql);
    } while (!$randomSql);
    
    // Strip the image url out of the content
    $randomImage =substr($randomChoice->post_content,strpos($randomChoice->post_content,'<img'));
    $randomImage =substr($randomImage,strpos($randomImage,'src="')+5);
    $randomImage =substr($randomImage,0,strpos($randomImage,'"'));
    
    //  Output the link and image
    
    echo '<a href="'.$baseurl.'/?p='.$randomChoice->ID.'" title="Read the full story"><img src="'.$randomImage.'" width="100px" alt="Random picture" /></a>';
    ?>


    You could, of course, amend the sql to only choose pictures from a specified blog(s), limit it to published posts, posts in certain catagories etc, without much more work

    I'm sure there are cleaner ways to do this, but as I said, my knowledge of php is zero.

    ?

    6 Feb 13, 2005 14:17

    ????? d???? doo!

    BAH ... Pretty smitty ... if it works & doesn't leave a gaping hole in the side of the database, it's good enuff for me!

    You're being waaay too modest, ?????. I wish I had half the 'zero' knowledge you have ... cause if this's zero? ... what one can do with just 20% :lol:

    thank you ... thank you ... thank you. A starting point!

    I can see limiting it to just one DB, yes. I can also see selecting a random image from WITHIN the randomly chosen blog. But other than than ... BOOM ... you nailed it.

    I'll let you know how it works out. THANKS AGAIN!

    Edit - very interesting logic used to get the post using the random ID (> randID), because ... of course ... there are GAPS in the IDs.

    I could see that ceratain blog entries would be randomly chosen more often, if there is a gap in entry ID. Like my Id's don't start till 23 (guess I must've deleted an early bunch of 'test' posts). So whatever images are in ID=23 will be chosen when the random # is 1-22, whereas images in ID=24 would only be chosen if the random # is 23. Of course, I could pull a bottom limit too, cause the other ID gaps aren't that big ... once you get rolling with B2, they're pretty much sequential.

    It's getting scary! This stuff is starting to make SENSE to me! lol

    7 Feb 13, 2005 15:16

    Told you my sql wasn't good, if you know how to create a table in sql then you could amend the code to

    create a temp table - fields id, post_id,comment
    add a record for every comment with an image tag
    choose a random number between 0 and #records-1 in temp table
    delete temp table

    Then your gaps wouldn't matter :p

    I'll root round the sql site and see if I can find out the missing bits ;)

    8 Feb 13, 2005 15:47

    A couple of blind mice? Ha ha.

    In trying to count the number of occurrences of "<img" in post_content (which isn't as straight forward as one would assume) I ran into this at:

    http://www.samspublishing.com/articles/article.asp?p=30875&seqNum=9

    "Versions of MySQL from 3.23.23 on include the capability for performing full text searches. The full text search engine allows you to look for words or phrases without using pattern-matching operations."

    "A FULLTEXT index is created the same way as other indexes. That is, you can define it with CREATE TABLE when creating the table initially or add it afterward with ALTER TABLE or CREATE INDEX. Because FULLTEXT indexes require you to use MyISAM tables, you can take advantage of one of the properties of the MyISAM handler if you're creating a new table to use for FULLTEXT searches:"

    With an example:

    CREATE TABLE apothegm (attribution VARCHAR(40), phrase TEXT);
    LOAD DATA LOCAL INFILE 'apothegm.txt' INTO TABLE apothegm;
    ALTER TABLE apothegm
      ADD FULLTEXT (phrase),
      ADD FULLTEXT (attribution),
      ADD FULLTEXT (phrase, attribution);

    Dunno if this will help?

    9 Feb 13, 2005 16:26

    Lol, that's double dutch to me, but I did come up with an amended version which uses a temp table to store all posts with <img>

    
    <?php
    $randomSql="create table evo_temp (ID integer(4) auto_increment,post_id integer(4),content text(65535),primary key(ID))";
    $DB->query($randomSql);
    $randomSql="insert into evo_temp (post_id,content) select ID,post_content from T_posts where post_content like '%<img%'";
    $DB->query($randomSql);
    $randomSql="select ID from evo_temp order by ID desc limit 0,1";
    $randomRecord=$DB->get_row($randomSql);
    
    $randomSql="select ID,post_id,content from evo_temp where ID > '$randomRecord-1' limit 0,1";
    $randomChoice=$DB->get_row($randomSql);
    $randomImage =substr($randomChoice->content,strpos($randomChoice->content,'<img'));
    $randomImage =substr($randomImage,strpos($randomImage,'src="')+5);
    $randomImage =substr($randomImage,0,strpos($randomImage,'"'));
    echo '<a href="'.$baseurl.'/?p='.$randomChoice->post_id.'" style="border:0" title="Read the full story"><img src="'.$randomImage.'" width="100px" alt="Random picture" /></a>';
    $randomSql="drop table evo_temp";
    mysql_query($randomSql);
    ?>

    11 Feb 13, 2005 17:37

    I've noticed that you have an error with the code on your blog, try editing this line (remove the red bit) and see if it cures it

    $randomSql="create table evo_temp (ID integer(4) auto_increment,post_id integer(4),content text(65535),primary key(ID))";

    12 Feb 13, 2005 19:05

    Yeah, I found that already. Assumes a 64k size for text by default.

    Also, you can make a table with "CREATE TEMPORARY TABLE", which will automatically be dropped.

    I've been fiddling with the fulltext index searching and it's not much good (only finds text - abc, 123, apostrophe's and underscores - ignores if not bordered by spaces). NOT much good in counting occurances of "<img" :-/ (or anything else in HTML code language, for that matter).

    HA ... back to STRINGS. (bleck)

    13 Feb 13, 2005 19:46

    How about adding a category for posts with pics that you want in the random display then doing your first search joined to postcats where postcat_cat_ID = N? You could then count the results of that query as the max for your random number, then pull that item from the query.

    14 Feb 13, 2005 20:08

    Not too keen on having a new category to check off when I make posts (forget to check the ones I got already). Of course, the nice thing about that method would be that you controlled WHICH posts were eligible for the random image thing.

    I think the temp table thing is working okay, got my INSERT statement all set, just working on counting the occurrences of images in each post (so I can randomly choose from THOSE as well).

    INSERT INTO evo_temp( post_id, content ) 
    SELECT ID, post_content
    FROM evo_posts
    JOIN evo_categories ON ( post_category = cat_ID ) 
    WHERE post_content LIKE "%<img%"
    AND cat_blog_ID =7 

    Finally have a way to count occurrences, but I cannot honestly believe it's the best way!

    SELECT ROUND((length(content)-length(replace(content,'<img','')))/4) as total from evo_temp where ID='$randomSql'

    I tested w/a hardcoded post_id number, but think that's the right random variable. ;)

    Now, all I gots to do is put it together :) Thanks ?????

    Almost home ....

    15 Feb 13, 2005 23:50

    Success (and a question):

    First ... YAY! I got it to work. Here's the code

    
    <?php 
    
    // starting stuff
    mysql_query("DROP TABLE evo_temp");
    
    // create a temp table - fill w/posts that have pics (blog #7 only)
    mysql_query('create table evo_temp ( ID integer(4) auto_increment, post_id integer(4), content text, primary key (ID) )'); 
    $imgBlogs = mysql_query ("insert into evo_temp (post_id,content) select ID,post_content from $tableposts join $tablecategories on (cat_ID=post_category) where cat_blog_ID=7 AND post_content like '%<img%'"); 
    
    // get total num of blogs w/pics - select one randomly
    $r = mysql_query ("select * from evo_temp");
    $maxEntry = mysql_num_rows($r);
    $randomPost=mt_rand(1,$maxEntry);
    
    // extract the image file location for the randomly chosen image
    $r = mysql_query ("select ID,post_id,content from evo_temp where ID=$randomPost");
    $randomContent = mysql_fetch_row($r);
    $times = substr_count($randomContent[2],"<img"); // Num of pics in the random blog
    
    $randomImg = substr($randomContent[2],strpos($randomContent[2],'<img'));
    $randomImg = substr($randomImg,strpos($randomImg,'src="')+5);
    $randomImg = substr($randomImg,0,strpos($randomImg,'"'));
    
    // add the link and the image
    echo '<a class="randPicLnk" href="'.$baseurl.'/?p='.$randomContent[1].'" title="Read the full story"><img src="'.$randomImg.'" style="width:150px; border:1px solid #339;" alt="Random picture" /></a>'; 
    
    // ending stuff
    mysql_query("DROP TABLE evo_temp");
    ?> 

    The question: Right now, this only selects the FIRST pic in a random blog. I've added the count for the number of images in the random blog, but I don't know how to extract the image information for the Nth occurrence. (Need to add a random thing for the images on the page too, but I know how. ) What's got me stumped is:

    How do you loop through, selecting the 2nd, 3rd, 4th, Nth occurrence of "<img" from the randomImg[2]?

    I'm thinking that it might be a solution (don't know if this the correct syntax), but here goes ...

    
    $start=0;
    $offset=0;
    do while $start<($times-1);
    if ($start=$times-1) { extract img file loc like above; } else {
    $loc=strpos($randomImg[2],"<img",$offset);
    $offset=$loc+10;
    loop
    

    Not sure if this is the correct use of offset, but couldn't you SKIP PAST the first occurrence (now that you know where it is)? I DO know, my loop construct is lame (because I've never made a php loop before!) :)

    Help! THX.

    16 Feb 14, 2005 11:05

    $randomContent = mysql_fetch_row($r);
    $times = explode("<img",$randomContent[2]); // Num of pics in the random blog
    $randomImg=$times(mt_rand(2,count($times));
    $randomImg = substr($randomImg,strpos($randomImg,'src="')+5);
    $randomImg = substr($randomImg,0,strpos($randomImg,'"'));

    17 Feb 14, 2005 23:45

    Got it - Thank you ????? !

    Thanks for turning me on to the 'explode' function. Had some probs w/indexing, but in the end, it all worked out. Here's the final code AND where you can [url=http://randsco.com]see it in action[/url]:

    <?php 
    
    // create a temp table & fill it w/posts having pics (from main blog only)
    mysql_query('create temporary table evo_temp ( ID integer(4) auto_increment, post_id integer(4), content text, primary key (ID) )'); 
    $imgBlogs = mysql_query ("insert into evo_temp (post_id,content) select ID,post_content from $tableposts join $tablecategories on (cat_ID=post_category) where cat_blog_ID=7 AND post_status='published' AND post_content like '%<img%yyy%'"); 
    
    // get total numbr of blogs w/images & randomly select one
    $r = mysql_query ("select * from evo_temp");  // get everything from temp DB
    $maxEntry = mysql_num_rows($r);               // count rows
    $randomPost=mt_rand(1,$maxEntry);             // choose random row
    $r = mysql_query ("select ID,post_id,content from evo_temp where ID=$randomPost");  // pull data from random row
    $randomContent = mysql_fetch_row($r);         // stuff it into a variable
    
    // find # pics in random blog & randomly select one
    $numImgs = explode('<img class="yyy" ',"$randomContent[2]"); // chop blog text into chunks, each chunk starting w/(<img style="yyy")
    $randomImg = mt_rand(1,count($numImgs)-1);      // randomly choose an img chunk
    $randomImg = $numImgs[$randomImg];              // stuff it into a variable
    
    // extract pic location 
    $randomImg = substr($randomImg,strpos($randomImg,'yyy" src="')+10); // find position just beyond [src="]
    $randomImg = substr($randomImg,0,strpos($randomImg,'"'));     // extract everything between double quotes
    
    // add the link and the image
    echo '<a class="randPicLnk" href="'.$baseurl.'/?p='.$randomContent[1].'" title=" Click for &quot;The Rest of the Story&quot; "><img src="'.$randomImg.'" style="width:160px; border:1px solid #339;" alt=" Click for &quot;The Rest of the Story&quot; " /></a>'; 
    
    ?> 

    I liked EdB's idea of controlling WHICH images get chosen for random posting, so I modified the code a bit, to allow for a filter. IF you want the image to be selected, just make sure you have

    <img class="yyy" src = "blah, blah, blah" />

    in the img link, otherwise, use:

    ,img class="no" src ="blah, blah, blah" />

    'class' needs to come immediately after 'img', with 'yyy' IF you want it as a choice.

    EDIT 21-Feb-05: Just discovered that the CSS validator does not like the style="no/yyy" and will fail. Why? Because there is no such property called "no" or "yyy". Makes sense. :oops: FIX: use class= instead of style= :D --- I changed the code (above) so you can still cut-n-paste into your _main.php file.

    EDIT 21-Feb-05: Today's a big day for finding stuff. ;) For the first time, I posted a draft & noticed that whatever picture in the draft was being selected by the random SQL query. So I fixed that (above) by selecting only PUBLISHED blogs.

    Thanks ????? ... I could NOT have done it with out your help.

    Cheers

    18 Feb 15, 2005 00:36

    Still think yer php/mysql knowledge is zero ? ;)

    Glad to see you got it working :)

    ?

    19 Feb 15, 2005 03:24

    It's IMPROVING :roll:

    Still ... 10 X ZERO still equals ZERO :lol:

    Thanks a TON for your help!!

    20 Feb 15, 2005 11:32

    You're more than welcome, I learnt a thing or to myself as well :D

    21 Feb 12, 2007 14:59

    Hmmm, I have found the script here, read the instruction twice and tried to implement it in my blog... I only replayed yyy with pix because I find it nicer...

    I edited cat_blog_ID=3 and translated the image title to my language... besides I left the script as it is...

    I edited two of my own postings with <div class="image_block"><img class="pix" src="http://... and modified the custom.css file like follows:

    /* Styles for random sidebar image linked to corresponding blog entry */
    pix { }
    randPicLnk { border: none; width: 220px; }

    But... it doesn´t work... Instead of a random picture I get:

    Warning: mysql_num_rows(): supplied argument is not a valid MySQL result resource in /home/www/web111/html/blog/skins/custom/_main.php on line 213
    
    Warning: mysql_fetch_row(): supplied argument is not a valid MySQL result resource in /home/www/web111/html/blog/skins/custom/_main.php on line 216
    
    Notice: Undefined offset: 1 in /home/www/web111/html/blog/skins/custom/_main.php on line 221

    What is wrong? What do I have to do otherwise?

    And when someone could help me correct the script, how is it possible to make a quick-tag toolbar button in the back office that generates the <img> tag code (and includes a class="pix" by default)?

    I hope somebody can help me...

    Thank you in advance...
    Daniel

    22 Feb 19, 2007 16:32

    It'll be easier to work with you via email, which is what I've been doing.

    I'm sure I can get it working for you, just need to come round and have a quick look at the script and your DB setup.

    Cheers,

    23 Aug 19, 2007 16:01

    Several month ago I had problems to get this working... but after I re-wrote the script nearly from scratch - looking afer every line to your code ;) - it´s working now well for month...

    The script only choosed images from postings in selected blogs which are released and have a certain string after the IMG-tag... so far so good. But when I publish some posts in the future - setting the date manually into the future so that the posting will appear e.g. tomorrow or something like that - the included images can appear as a random picture as well... That´s not good, because when I click on such an image, you get an error message that this posting is not available - sure, it´s not yet the future :lol:

    But preparing my blog for my holidays, is it possible to improve the script, so that only posts will be choosen, which are already visible on the page, so not dated in the future?

    <?php
    
    if( !defined('EVO_MAIN_INIT') ) die( 'Please, do not access this page directly.' ); 
    
    mysql_query('drop table evo_randpic');
    
    // create a table & fill it with posts having pics
    mysql_query("create table evo_randpic ( ID integer(4) auto_increment, post_id integer(4), content text, title text, primary key (ID) )"); 
    mysql_query("insert into evo_randpic ( post_id, content, title ) select post_id, post_content, post_title from evo_posts join evo_categories on ( cat_ID = post_main_cat_ID ) where post_status='published' AND post_content like '%randpix%'"); 
    
    // get total num of blogs with images & randomly select one 
    $r = mysql_query ("select * from evo_randpic"); 						// get everything from temp DB
    $maxEntry = @mysql_num_rows($r); 								// count rows
    $randomPost = mt_rand(1,$maxEntry); 								// choose random row
    $r = mysql_query ("select ID, post_id, content, title from evo_randpic where ID=$randomPost");  // pull data from random row
    $randomContent = @mysql_fetch_row($r); 								// stuff it into a variable
    
    // find total num of pics & randomly select one 
    $numImgs = explode('<img class="randpix"',"$randomContent[2]"); 				// chop entry right after <img src=
    $randomImg = mt_rand(1,count($numImgs)-1); 							// randomly choose an img chunk
    $randomImg = $numImgs[$randomImg]; 								// stuff it into a variable
    
    // extract pic location 
    $randomImg = substr($randomImg,strpos($randomImg,'randpix" src="')+13); 			// find position just beyond [src="]
    $randomImg = substr($randomImg,0,strpos($randomImg,'"')); 					// extract everything between double quotes
    
    // test script elements if correct
    // echo "path=", $randomImg;									// to see if img path is correct
    // echo "postID=", $randomContent[1];								// to see if postID is correct
    // echo "title=", $randomContent[3];								// to see if title is correct
    
    // add the link and the image in the tv-border
    	echo '...';
    ?>

    I can´t figure that out... can anybody help me here?

    Thank you very much in advance,
    Daniel

    24 Aug 19, 2007 17:15

    Daniel,

    This can be handled by adding a bit more to your WHERE clause. I'm not 100% on the syntax, but the logic is something like:

    
    mysql_query("insert into evo_randpic ( post_id, content, title ) select post_id, post_content, post_title from evo_posts join evo_categories on ( cat_ID = post_main_cat_ID ) where post_status='published' AND post_datestart < now() AND post_content like '%randpix%'");
    

    Off to breakfast. Hope this helps.

    -stk

    25 Aug 19, 2007 17:49

    Thanks stk, I´ve added the AND post_datestart < now() and the script still works... :D

    If it does the job I need - I don´t know... because I´ve seen the above described problem by accident... and because I now have hundrets of postings but only a one or two in the future, it´s hard to check... but nevertheless... everything is still working and the new piece of code can only help...

    Thanks again and enjoy your breakfast...
    Daniel

    26 Jun 12, 2008 18:20

    Does anybody know how to put the code into a widget?

     <?php
    
    if( !defined('EVO_MAIN_INIT') ) die( 'Please, do not access this page directly.' ); 
    
    mysql_query('drop table evo_randpic');
    
    // create a table & fill it with posts having pics
    mysql_query("create table evo_randpic ( ID integer(4) auto_increment, post_id integer(4), content text, title text, primary key (ID) )"); 
    mysql_query("insert into evo_randpic ( post_id, content, title ) select post_id, post_content, post_title from evo_posts join evo_categories on ( cat_ID = post_main_cat_ID ) where post_status='published' AND post_content like '%randpix%'"); 
    
    // get total num of blogs with images & randomly select one 
    $r = mysql_query ("select * from evo_randpic");                         // get everything from temp DB
    $maxEntry = @mysql_num_rows($r);                                 // count rows
    $randomPost = mt_rand(1,$maxEntry);                                 // choose random row
    $r = mysql_query ("select ID, post_id, content, title from evo_randpic where ID=$randomPost");  // pull data from random row
    $randomContent = @mysql_fetch_row($r);                                 // stuff it into a variable
    
    // find total num of pics & randomly select one 
    $numImgs = explode('<img class="randpix"',"$randomContent[2]");                 // chop entry right after <img src=
    $randomImg = mt_rand(1,count($numImgs)-1);                             // randomly choose an img chunk
    $randomImg = $numImgs[$randomImg];                                 // stuff it into a variable
    
    // extract pic location 
    $randomImg = substr($randomImg,strpos($randomImg,'randpix" src="')+13);             // find position just beyond [src="]
    $randomImg = substr($randomImg,0,strpos($randomImg,'"'));                     // extract everything between double quotes
    
    // test script elements if correct
    // echo "path=", $randomImg;                                    // to see if img path is correct
    // echo "postID=", $randomContent[1];                                // to see if postID is correct
    // echo "title=", $randomContent[3];                                // to see if title is correct
    
    // add the link and the image in the tv-border
        echo '...';
    ?> 

    Thanks

    27 Jun 12, 2008 19:02

    Wow how the times have changed, that code could be so simplified now that I know far more about mysql.

    Converting it to a widget pretty much means "slap it in function SkinTag()" ... if I get a chance I'll rattle something off.

    ¥

    28 Jun 14, 2008 23:07

    ok, that would be great. thanks.

    29 Dec 27, 2008 22:37

    Daniel wrote:

    Several month ago I had problems to get this working... but after I re-wrote the script nearly from scratch - looking afer every line to your code ;) - it´s working now well for month...

    hi!
    How did you get rid of the
    Notice: Undefined offset: 1 in index.main.php
    ? ?

    I used the code you posted and I keep getting this notice :'(

    this is the line that doesn't want to behave :

    $randomImg = $numImgs[$randomImg];  

    30 Dec 28, 2008 09:09

    We've since made this into a plugin, I'll have to see if I can find it ;)

    ¥

    31 Dec 28, 2008 12:10

    Thank you!
    That would be loverly :)

    32 Dec 28, 2008 14:27

    Ack, it's a smidge hard-coded for scotts blog, until I get round to adding some settings you'll need to play with the following, shich is the plugins SkinTag() functions code ) and adjust the blog id, title, etc to suit

    <?php
    		global $DB;
    		$sql = 'SELECT post_ID FROM T_items__item JOIN T_categories ON (cat_ID=post_main_cat_ID) WHERE cat_blog_ID=7 AND post_status=\'published\' and post_content like \'%<img%yyy%\' ORDER BY RAND() LIMIT 1';
    		if( $post = $DB->get_var( $sql ) )
    		{
    			$ItemCache = get_Cache( 'ItemCache' );
    			$imgItem = $ItemCache->get_by_ID( $post );
    			preg_match_all( '~(<img[^>]+?yyy"[^>]+?>)~', $imgItem->get( 'content' ), $imgs );
    			shuffle( $imgs[1] );
    			echo '<div id="randomImage">
    		<h3>Random Photo<span> (linked to blog entry)</span></h3>
    		<a href="'.$imgItem->get_permanent_url().'"><img title=" Read the Journal Entry containing this photo " alt=" random image &amp; link to blog entry " '.preg_replace( '~^.+?(src="[^"]+?").+?$~', '$1', $imgs[1][0] ).'/></a>
    		</div>';
    }
    ?>

    ¥

    33 Dec 28, 2008 15:15

    Thank you! That was quick!

    I adjusted blog number, tables names, image title and style, etc... and put the code in my index.main.php file...
    Unfortunately it doesn't work :
    I get a "Parse error: syntax error, unexpected $end in index.main.php on line 442
    "
    message.

    said line is the end of the main.php file :

    
             440<?php 
             441   exit;
             442     ?>
    

    I don't understand what went wrong, I get the same message if I change nothing from your code, just a blank page and this message.

    Can you help me again?
    Please?

    oh! Wait!

    I think there was a closing bracket missing... looks like it works now

    34 Dec 28, 2008 15:21

    *cough* I missed a } before ?> I'll correct my original post ;)

    ¥

    36 Dec 28, 2008 15:37

    No worries ;)

    offtopic : you may wish to consider adding a width to your wrapper and centering it as it looks a smidge *disjointed* at my res ;)

    #skin_wrapper{
    width:1000px;
    margin:0 auto;
    }

    37 Dec 28, 2008 15:41

    This looks like a good gadget Mr Y, as ever.

    Am I right that it will read through the entire DB looking for image files? If so, is this the sort of thing I should be cautious in using on a high-traffic blog (with over 200 posts with images on)?

    38 Dec 28, 2008 15:44

    Well, there's only one way to find out for sure :D, but it *should* have minimal impact as it's just a single mysql query ( run a timer on it, that should tell you )

    ¥

    39 Dec 28, 2008 16:02

    ¥åßßå wrote:

    No worries ;)

    offtopic : you may wish to consider adding a width to your wrapper and centering it as it looks a smidge *disjointed* at my res ;)

    #skin_wrapper{
    width:1000px;
    margin:0 auto;
    }

    Done!

    Thank you for the advice and your help! :D


    Form is loading...