# PHP Random Image script...



## Brian07002 (Sep 15, 2011)

Hello,

I would like to display a random image from a folder (containing 250 images) but I only want to display one random image based on a 24 hour period. Ex: At 12:00am (midnight) I want the next image to display for another 24 hours and so on...

Can someone post a relevant code to do that in php?

Thank you
Brian


----------



## Corday (Mar 3, 2010)

Java would need written code(complicated). PHP mavens have already written programs, some free. Google: make my website rotate random images php


----------



## Brian07002 (Sep 15, 2011)

Corday said:


> Java would need written code(complicated). PHP mavens have already written programs, some free. Google: make my website rotate random images php


I already tried googling, all day in fact, and I have seen several scripts, and have even tried following the tutorials, but the tutorials have only been to rotate random images but not every 24 hours...

I need to display one image a day (every 24 hours) from a folder of at least 250 images and display the image in my header. These images are not stored in a db, they will be stored locally on the hard drive. As a side note: Do you think putting the images in a mysql db would be a better option in this case since there are 250 images? Basically, this will be for the header of my website.

Thank you
Brian


----------



## Brian07002 (Sep 15, 2011)

I seen this one earlier:


```
<?php
$dayofyear = date('z');

// test it
echo 'Today is day number ' . $dayofyear ;
?>

<img src="/images/<?php echo $dayofyear ?>.jpg" />
```
Problem with this one is, I don't have 365 images...But it's the closest I have seen to my requirement. :banghead: 

Brian


----------



## Brian07002 (Sep 15, 2011)

Based on this Code: 


```
$hour = date('H', time());
    
    if( $hour > 6 && $hour <= 11) {
      echo "Good Morning";
    }
    else if($hour > 11 && $hour <= 16) {
      echo "Good Afternoon";
    }
    else if($hour > 16 && $hour <= 23) {
      echo "Good Evening";
    }
    else {
      echo "Why aren't you asleep?  Are you programming?";
    }
```
How can I display a random image from a folder of 250 image or possibly more on a 24 hour period? Another words, I want to display (at random) one image every 24 hours. A new image will replace the current one at 12:00am everyday?

Edit: I have also tried this script for pngs, but no luck: 


```
function getImageOfTheDay() {
    $myDir = "path/to/images/";
    $day = sprintf("1%03d%d", date('z'), date('Y'));
    $jpgs = glob($myDir . "*.jpg");
    return $jpgs[$day % count($jpgs)];
}
```


----------



## Brian07002 (Sep 15, 2011)

I have tried this tutorial as well: 
https://gist.github.com/projectxcappe/1220777/9ec6a7e62fb9d7c9a93bd834fb434d7ae25ed6f5


----------



## Brian07002 (Sep 15, 2011)

Here's a new one I found which by subject is exactly what I want to do, but unfortunately I haven't been able to get it working...I am using php 7 which is probably why...

https://stackoverflow.com/questions...an-image-at-12-midnight-every-day/68281#68281

Post by nickf answered Sep 16 '08 at 0:39

Goto that page on stackoverflow, and look for nickf with the date above, just copy/paste the url, then search for that date, it will have his code posted above.


----------



## Corday (Mar 3, 2010)

Did you try first without the last two lines changed?


----------



## Brian07002 (Sep 15, 2011)

Corday said:


> Did you try first without the last two lines changed?


Yes. Did not work. :frown:


----------



## Corday (Mar 3, 2010)

I reached out to staff this morning, but no response yet. Are images all in the same format, i.e. .jpeg? Are they sequentially numbered?


----------



## Brian07002 (Sep 15, 2011)

Corday said:


> I reached out to staff this morning, but no response yet. Are images all in the same format, i.e. .jpeg? Are they sequentially numbered?


All images are PNG format
Images are NOT sequentially numbered

Thank you
Brian


----------



## Corday (Mar 3, 2010)

Someone else is taking a look. Numbered sequence is in my mind, but I don't know why.


----------



## Brian07002 (Sep 15, 2011)

Corday said:


> Someone else is taking a look. Numbered sequence is in my mind, but I don't know why.


Thanks man! I appreciate your time! Do you think sometime tonight you will get back to me? It's about 10 minutes after 5pm my time right now.


----------



## wmorri (May 29, 2008)

So I started to work on this a little bit. I don't write straight php much anymore, but here is something I thought might work.


```
<?php

$d = date('j'); // set variable $d to day of the month

if($d >= 0){
function random_pic($dir = 'images') { // set the directory of your images
  $files = glob($dir . '\*.*'); // grab all files from the directory set by $dir
  $file = array_rand($files); // randomly choose a file from all the files in $dir
  return $files[$file];
    };
};

?>
```
Not sure if this is something that would work for you. Just thought I would throw it out there.


----------



## Brian07002 (Sep 15, 2011)

wmorri said:


> So I started to work on this a little bit. I don't write straight php much anymore, but here is something I thought might work.
> 
> 
> ```
> ...


Tried it, no errors, but no images are displaying either :sad: I checked the path to make sure it was correct, but still nothing showing. Also, I see your using php date function...I was thinking more along the lines of php time function, as I want to display a new image every 24 hours, not once a month if that is how your code is meant to work, I have looked it up, but I don't know php that well...


----------



## axe0 (Jun 15, 2016)

Brian07002 said:


> I already tried googling, all day in fact, and I have seen several scripts, and have even tried following the tutorials, but the tutorials have only been to rotate random images but not every 24 hours...
> 
> I need to display one image a day (every 24 hours) from a folder of at least 250 images and display the image in my header. These images are not stored in a db, they will be stored locally on the hard drive. As a side note: Do you think putting the images in a mysql db would be a better option in this case since there are 250 images? Basically, this will be for the header of my website.
> 
> ...


IMO it's better to put the image location into a database and use the location. Storing the image itself into a database will slow down your page significantly, using the location will prevent future issues when a site is being moved.


If you want to automatically display a new random image I would recommend to make a table in the database for this, that is if you haven't already done so.

The random_pic function needs to be stored in a variable for it to work, below is some working code that will show a random image on each refresh, a simple check with a db connection to see whether or not the day has passed and retrieving img location (and updating it in the db if the day has passed) would be all you need.


```
$d = date('j'); // set variable $d to day of the month

if($d >= 0){
    function random_pic($dir = 'images') { // set the directory of your images
        $files = glob($dir . '\*.*'); // grab all files from the directory set by $dir
        $file = array_rand($files); // randomly choose a file from all the files in $dir
        return $files[$file];
    };
};

$img = random_pic(); // store the image into variable
echo "<img src='$img'/>";
```

This is how I would do it, it may not be 100% bug free, it's been a while since I've written any db connection without a framework like laravel or symfony, but it should give an indication.

```
$conn = new mysqli('localhost', 'root', '', 'db'); // connect to db
$data = $conn->query('select * from `table`')->fetch_all(); // get everything, logically there's only 1 row to fetch

if($data['timestamp'] != date('Y-m-d')){ // is stored date different from current date, if get new image and store it's location
    function random_pic($dir = 'images') { // set the directory of your images
        $files = glob($dir . '\*.*'); // grab all files from the directory set by $dir
        $file = array_rand($files); // randomly choose a file from all the files in $dir
        return $files[$file];
    };

// Prepare query to update db
    $stmt = $conn->prepare('update table set img= :img timestamp = current_date ');
    $stmt->bind_param(':img', $img); // tell connection to expect the data be stored in $img variable
    $img = random_pic(); // store the data
    $stmt->execute(); // save the data
    $stmt->close();
}

// no matter what happens, the updated or current image will be retrieved
$img = $data['img'];

echo "<img src='$img'>"; // use the data
```


----------



## Brian07002 (Sep 15, 2011)

axe0 said:


> IMO it's better to put the image location into a database and use the location. Storing the image itself into a database will slow down your page significantly, using the location will prevent future issues when a site is being moved.
> 
> 
> If you want to automatically display a new random image I would recommend to make a table in the database for this, that is if you haven't already done so.
> ...


I definitely agree with your statement regarding storing the image location in the db rather than the image itself being stored in the db. I don't mean to tangle your thoughts as I am not a programming by design, but I have studied this years back, over a decade ago, but have lost some of my thoughts on this stuff, but now that you brought back that memory, could you make it so that it could work off a table inside a mysql db, instead of just using a folder?

Thank you for your replies and continued support!
Brian


----------



## axe0 (Jun 15, 2016)

Here's some updated code

```
// The SQL table structure, simply copy & paste it
// create TABLE test (id int AUTO_INCREMENT not null, image varchar(255) not null, storedDate date not null, PRIMARY key(id));

function random_pic($dir = 'images') { // set the directory of your images
    $files = glob($dir . '\*.*'); // grab all files from the directory set by $dir
    $file = array_rand($files); // randomly choose a file from all the files in $dir
    return $files[$file];
};

$img = random_pic(); // we'll only use this to store the file location in the database

$conn = new mysqli('localhost', 'root', '', 'db'); // connect to db
$data = $conn->query('select * from `test`')->fetch_assoc(); // get everything, logically there's only 1 row to fetch

if(count($data) == 0){ // no data stored in the db, this will only be the case the first time
    $time = date("Y-m-d"); // store the date, only variables can be used as reference in bind_param
    $stmt = $conn->prepare('insert into test (image, storedDate) values(?, ?);');
    $stmt->bind_param('ss', $img, $time); // tell the query to use these variables as reference (bind_param only uses them as reference)
    if(!$stmt->execute()){
        echo "error:" . $stmt->error; // if for some reason the query fails, give us the reason why it fails
    }
    $stmt->close(); // close this connection, we don't need it anymore.

    // Redo the query to overwrite the data if the query got us nothing
    $data = $conn->query('select * from `test`')->fetch_assoc(); // get everything, logically there's only 1 row to fetch
}

if($data['storedDate'] != date('Y-m-d')){ // is stored date different from current date, if so update the image with new images stored in $img

// Prepare query to update db
    $stmt = $conn->prepare('update table set image = ? timestamp = current_date ');
    $stmt->bind_param('s', $img); // tell connection to expect the data be stored in $img variable
    $stmt->execute(); // save the data
    $stmt->close(); // close it again
}
$conn->close(); // close the last open connection, we don't want someone to use it

echo "<img src='$data[image]'>"; // use the data
```


----------



## Brian07002 (Sep 15, 2011)

axe0 said:


> Here's some updated code
> 
> ```
> // The SQL table structure, simply copy & paste it
> ...


I just want to be sure about something before I continue...Do I have to specify the location of each of my images in the image column in the db, or does your script automatically add the image location from the php script? I don't mind adding the locationss, I just need to know if that step is required...Sorry if it sounds like a Noob question...Just thought I'd ask...

As a side note: I put two image url's in the db, and then I tried the script, one image displayed perfectly, but then I tried to advance my system date one day, and the script drew a blank page when I refreshed...Is that the correct response from your php script, or am I doing something wrong?

Brian


----------



## axe0 (Jun 15, 2016)

The way I thought about it, and have written it, is that there is only 1 entrie in the db which is the actively used file.

This part of the code inserts the first used filename as location in the db if there are no entries in the db, it will do so only once and so after the first entry it can be commented out.

```
if(count($data) == 0){ // no data stored in the db, this will only be the case the first time
    $time = date("Y-m-d"); // store the date, only variables can be used as reference in bind_param
    $stmt = $conn->prepare('insert into test (image, storedDate) values(?, ?);');
    $stmt->bind_param('ss', $img, $time); // tell the query to use these variables as reference (bind_param only uses them as reference)
    if(!$stmt->execute()){
        echo "error:" . $stmt->error; // if for some reason the query fails, give us the reason why it fails
    }
    $stmt->close(); // close this connection, we don't need it anymore.

    // Redo the query to overwrite the data if the query got us nothing
    $data = $conn->query('select * from `test`')->fetch_assoc(); // get everything, logically there's only 1 row to fetch
}
```
The other if statement updates the filename in the db if 'storedDate' does not match.

I don't know how you thought about it, but I didn't see a need where multiple filenames are stored in te db. It is currently basically the same as with multiple filenames, only there are less additional checks required.


----------



## Brian07002 (Sep 15, 2011)

axe0 said:


> The way I thought about it, and have written it, is that there is only 1 entrie in the db which is the actively used file.
> 
> This part of the code inserts the first used filename as location in the db if there are no entries in the db, it will do so only once and so after the first entry it can be commented out.
> 
> ...


I am sorry, but I don't quite understand what you mean, as I have tried using your code without adding anything into the db, and I received 

```
error:Column 'image' cannot be null
```
then, I edited the db and manually adjusted the image column, then the date and it did work as it did yesterday (my time, it's Friday 4-13 6:05am right now), but how can I make it so that I don't have to change image images in the db all the time, or am I working this script incorrectly?


----------



## Brian07002 (Sep 15, 2011)

Another words, with your script, I have to add the image url and the date, ok, adding the image url isn't a bad thing, but adding the date, that means if have to do that it will not be automatic, as I have to put the date in for each image...I think the key you didn't get from me was that the script *must* be automatic (every 24 hours or 12:00am each day) when displaying the images,


----------



## Brian07002 (Sep 15, 2011)

I was thinking along the lines of what this sitepoint.com post has: 

https://www.sitepoint.com/community/t/php-photo-of-the-day-per-day-every-year-script/25908

but my images will not be named in sequence, they will just be as they currently are named. Also, I will NOT HAVE 365 images, there will be less than that amount.


----------



## axe0 (Jun 15, 2016)

Brian07002 said:


> I am sorry, but I don't quite understand what you mean, as I have tried using your code without adding anything into the db, and I received
> 
> ```
> error:Column 'image' cannot be null
> ...


Everytime you load the page with PHP, the code is processed on the server and the server gives back a response which is what you see.



> Another words, with your script, I have to add the image url and the date, ok, adding the image url isn't a bad thing, but adding the date, that means if have to do that it will not be automatic, as I have to put the date in for each image...I think the key you didn't get from me was that the script *must* be automatic (every 24 hours or 12:00am each day) when displaying the images,


Just to clarify, the code was written to do exactly what you requested:
- get a random image name and changing each day
- display it.

I did get your 'key' feature, please read the comments I added in the code, I added a few comments to hopefully make it more clear that the code wmorri and I wrote fulfills the requirements of what you asked. 
There are 2 conditions
1. If the database is empty, insert the image name with the current date
2. If the database is not empty, update the image name with a new one if the stored date is not the current date. This will of course not happen as soon as a new day comes, but as soon as you (re)load the page on a new day.

As I mentioned, it's been a while since I manually wrote queries instead of using query builders, Eloquent (laravel) or doctrine (symfony) and noticed a few bugs. I fixed them, tested the code again and it once again works for me. I.e., it 
- gets a random image name from the folder 'images' and stores it in the database, each day is a different image
- displays the image

Updated code

```
//create TABLE test (id int AUTO_INCREMENT not null, image varchar(255) not null, storedDate date not null, PRIMARY key(id));

function random_pic($dir = 'images') { // set the directory of your images
    $files = glob($dir . '\*.*'); // grab all files from the directory set by $dir
    $file = array_rand($files); // randomly choose a file from all the files in $dir
    return $files[$file];
};

$img = random_pic(); // we'll only use this to store the file location in the database

$conn = new mysqli('localhost', 'root', '', 'db'); // connect to db
$data = $conn->query('select * from `test`')->fetch_assoc(); // get everything, logically there's only 1 row to fetch

// this will only be the case the first time, insert all data on first use or when the database is empty
if(count($data) == 0){
    $time = date("Y-m-d"); // store the date, only variables can be used as reference in bind_param
    $stmt = $conn->prepare('insert into test (image, storedDate) values(?, ?);');
    $stmt->bind_param('ss', $img, $time); // tell the query to use these variables as reference (bind_param only uses them as reference)
    if(!$stmt->execute()){
        echo "error:" . $stmt->error; // if for some reason the query fails, give us the reason why it fails
    }
    $stmt->close(); // close this connection, we don't need it anymore.

    // Overwrite data
    $data = $conn->query('select * from `test`')->fetch_assoc(); // get everything, logically there's only 1 row to fetch
}

// Update everything on a new day
if($data['storedDate'] != date('Y-m-d')){ // is stored date different from current date, if get new image and store it's location

// Prepare query to update db
    $stmt = $conn->prepare('update test set image = ?, storedDate = current_date;');
    $stmt->bind_param('s', $img); // tell connection to expect the data be stored in $img variable
    $stmt->execute(); // save the data
    $stmt->close(); // close it again
}
$conn->close(); // close the last open connection, we don't want someone to use it

echo "<img src='$data[image]'>"; // use the data
```


----------



## Brian07002 (Sep 15, 2011)

I am trying to test the script by advancing my clock to the 14th of april, but it's still showing the the same image.


----------



## Corday (Mar 3, 2010)

Brian07002 said:


> I am trying to test the script by advancing my clock to the 14th of april, but it's still showing the the same image.


Either let run for a day or set CMOS clock not Windows clock to test.


----------



## axe0 (Jun 15, 2016)

Using Windows clock to test it works perfectly for me.

Could you add the following and let me know what the results are please

```
var_dump($img, $data);
```
Place it before the first if statement or after the first if statement


----------



## Brian07002 (Sep 15, 2011)

axe0 said:


> Using Windows clock to test it works perfectly for me.
> 
> Could you add the following and let me know what the results are please
> 
> ...


I am getting no output except the image as I added one row into the db specifying the image url, and the date only, and I am getting just the image, but NO OUTPUT from the var_dump($img, $data); command.


----------



## axe0 (Jun 15, 2016)

How exactly are you running the script? Are you hosting it on a local server or online?


----------



## Brian07002 (Sep 15, 2011)

axe0 said:


> How exactly are you running the script? Are you hosting it on a local server or online?


I am in a testing environment http://localhost or http://192.168.1.5


----------



## Brian07002 (Sep 15, 2011)

axe0 said:


> Everytime you load the page with PHP, the code is processed on the server and the server gives back a response which is what you see.
> 
> 
> Just to clarify, the code was written to do exactly what you requested:
> ...





After waiting since yesterday, I just check the db, and the same data is in the db, and nothing else, nothing added or updated at all, and when I ran the php script, I get the same image as yesterday.


----------



## axe0 (Jun 15, 2016)

Brian07002 said:


> After waiting since yesterday, I just check the db, and the same data is in the db, and nothing else, nothing added or updated at all, and when I ran the php script, I get the same image as yesterday.


Did you open the page before or after checking the db?

Have you changed anything in the php.ini file?


----------



## Brian07002 (Sep 15, 2011)

axe0 said:


> Did you open the page before or after checking the db?
> 
> Have you changed anything in the php.ini file?


Sorry for late reply, just got in from work not too long ago...

I first opened the page to see if the random php script changed the image, and when I noticed that the image was still the same one, then I opened up https://localhost/phpmyadmin only to find that no other images were added. 

On a side note, I am using Ubuntu linux 16.04, not windows as I forgot to mention, and I did change my clock time (via the terminal) to see if that would make the script work, but I didn't see any changes from that either...I checked all of that this morning about 5:30am this morning my time (New York) I didn't notice the clock change when I adjusted it from my linux terminal yesterday, but this morning before I left for work, I realized the time was adjusted to 12:4?? I don't remember if it was 12 forty something am, but still no changes to the random.php script. 

Brian


----------



## axe0 (Jun 15, 2016)

> On a side note, I am using Ubuntu linux 16.04, not windows as I forgot to mention


Unless you updated some information on your profile we should know it, but I didn't take it into account. I believe Ubuntu has a few things different as opposed to Windows which could be why the script isn't working for you.
Luckily I have a Ubuntu 16.04 VM present, just need to install a few things and test the script. Hopefully I have tested (and possibly updated) the script later this evening or tomorrow.


----------



## Brian07002 (Sep 15, 2011)

axe0 said:


> Unless you updated some information on your profile we should know it, but I didn't take it into account. I believe Ubuntu has a few things different as opposed to Windows which could be why the script isn't working for you.
> Luckily I have a Ubuntu 16.04 VM present, just need to install a few things and test the script. Hopefully I have tested (and possibly updated) the script later this evening or tomorrow.


Ok, hopefully good news will come about from the script after you test on linux.


----------



## axe0 (Jun 15, 2016)

Code updated and tested in Ubuntu 16.04

```
const localhost = 'localhost';
const user = 'root';
const pass = '';
const db = ''; // fill in
const table = 'test';

$time = date('Y-m-d');
$query = 'select * from '.table;

function random_pic($dir = '/images/*.*') {
    $files = glob($dir);
    $file = array_rand($files);
    return $files[$file];
};
$img = random_pic();

$data = new mysqli(localhost, user, pass, db)->query($query);

if($data->num_rows == 0){
    $stmt = $conn->prepare('insert into '.table.' (image, storedDate) values(?, ?);');
    $stmt->bind_param('ss', $img, $time);
    if(!$stmt->execute()){
        echo "error:" . $stmt->error;
    }
    $stmt->close();
}

$data = $data->fetch_assoc();

if($data['storedDate'] != date('Y-m-d')){

    $stmt = $conn->prepare('update test set image = ?, storedDate = current_date;');
    $stmt->bind_param('s', $img);
    $stmt->execute();
    $stmt->close();
}
$conn->close();

// We'll need to query the db again to get fresh data
$data = new mysqli(localhost, user, pass, db)->query($query)->fetch_assoc();

echo "<img src='$data[image]'>";
```


----------



## Brian07002 (Sep 15, 2011)

axe0 said:


> Code updated and tested in Ubuntu 16.04
> 
> ```
> const localhost = 'localhost';
> ...


I am going to give this one a go now and see what happens. I will post back after completion. I wonder why I am getting nothing but a blank white page and you tested it on Ubuntu and it works? What do you think I am doing wrong? I have checked the db info was correct, and also the path to the images was correct. I am stumped, I will give it another try later or tomorrow.

Thank you for taking your time trying to get it man, I really do appreciate it!
Brian


----------



## axe0 (Jun 15, 2016)

Brian07002 said:


> I am going to give this one a go now and see what happens. I will post back after completion. I wonder why I am getting nothing but a blank white page and you tested it on Ubuntu and it works? What do you think I am doing wrong? I have checked the db info was correct, and also the path to the images was correct. I am stumped, I will give it another try later or tomorrow.
> 
> Thank you for taking your time trying to get it man, I really do appreciate it!
> Brian


At first I got a white page as well, I wrote a simple function to make debugging easy to find out where it went wrong.
The first thing I noticed was that I had to use the __DIR__ const to look in the images folder, which in turn forced me to use str_replace to remove the value added by __DIR__ to display a image properly.

Second issue was that I forgot to update the queries to reflect the table name change, so I defined a few consts for the connection and stored the select query in a variable, it prevented me from making typos and mistakes in forgetting to update the table name (db name is test, table name is test, caused confusion so I changed table name to testTable and forgot to update the queries), and removed a fetching that was uselessy adding extra load to the page.

Last thing I did was add the last fetching, without it the page needed to be refreshed 2 times to see the new image (update on first refresh, show update on second refresh).


----------



## axe0 (Jun 15, 2016)

Hi Brian,

I assume the updated code works?


----------



## Brian07002 (Sep 15, 2011)

axe0 said:


> Hi Brian,
> 
> I assume the updated code works?


Hello,
I am going to test the updated code right now, I was very tired yesterday, been working at my job away from computers, and it's been quite busy, so I had to rest up a bit, I am better so I will check now. Will post back shortly with a reply.

*UPDATE: I have tested by copying (verbatim, line by line) and pasting the latest code as a new file, should I have some of the old code in there as well? If not, I am still getting a blank page when running your latest code. 

Of course I have inserted the db name, and the user/pass for my db, and also update the path to my images, but still nothing...Oh wait, I didn't change the time to midnight...Let me post back....

Update: STILL NOT WORKING, GETTING A BLANK WHITE PAGE! :angry:
* 
Brian


----------



## axe0 (Jun 15, 2016)

A few questions:
- Is the database getting updated?
- What is the path stored in the database?
- Have you tried storing the path with __DIR__ and replacing __DIR__ with nothing when showing the image?


----------



## Brian07002 (Sep 15, 2011)

axe0 said:


> A few questions:
> - Is the database getting updated?
> - What is the path stored in the database?
> - Have you tried storing the path with __DIR__ and replacing __DIR__ with nothing when showing the image?



- Is the database getting updated?







MySQL returned an empty result set (i.e. zero rows). (Query took 0.0003 seconds.)

There are no rows in the test table in my database

- What is the path stored in the database?
I am not sure what you mean by this, if you mean where the images are stored, it's in the /flags/ folder

- Have you tried storing the path with __DIR__ and replacing __DIR__ with nothing when showing the image? I am not sure what you mean by this question, can you be more specific, and I will do it?

Brian


----------



## axe0 (Jun 15, 2016)

What is the error given? If no row is in the database and nothing is inserted, you must get an error.

__DIR__ is 1 of the predefined constants that shows the absolute path to the file it is used in, currently it works with the relative path what sometimes can cause issues if the coding isn't properly done. In the glob function simply concatenate __DIR__ with the $dir variable and when retrieving the path, use the str_replace function to change the absolute path to the relative path as the relative path is needed to show the image.


----------



## Brian07002 (Sep 15, 2011)

Hello,

I've turned on error_reporting in the php.ini file and I am getting this error in your script: 

*Parse error*: syntax error, unexpected '->' (T_OBJECT_OPERATOR) in */var/www/html/random.php* on line *19

*Here's the code I am using:

```
<?php 

const localhost = 'localhost';
const user = 'root';
const pass = '';
const db = 'db'; // fill in
const table = 'test';

$time = date('Y-m-d');
$query = 'select * from '.table;

function random_pic($dir = 'flags/*.*') {
    $files = glob($dir);
    $file = array_rand($files);
    return $files[$file];
};
$img = random_pic();

$data = new mysqli(localhost, user, pass, db)->query($query);

if($data->num_rows == 0){
    $stmt = $conn->prepare('insert into '.table.' (image, storedDate) values(?, ?);');
    $stmt->bind_param('ss', $img, $time);
    if(!$stmt->execute()){
        echo "error:" . $stmt->error;
    }
    $stmt->close();
}

$data = $data->fetch_assoc();

if($data['storedDate'] != date('Y-m-d')){

    $stmt = $conn->prepare('update test set image = ?, storedDate = current_date;');
    $stmt->bind_param('s', $img);
    $stmt->execute();
    $stmt->close();
}
$conn->close();

// We'll need to query the db again to get fresh data
$data = new mysqli(localhost, user, pass, db)->query($query)->fetch_assoc();

echo "<img src='$data[image]'>";  

?>
```


----------



## axe0 (Jun 15, 2016)

What PHP version are you using? If you don't know use phpinfo() to find out.


----------



## axe0 (Jun 15, 2016)

Brian07002 said:


> Hello,
> 
> I've turned on error_reporting in the php.ini file and I am getting this error in your script:
> 
> ...


See if this improves something.


----------



## Brian07002 (Sep 15, 2011)

axe0 said:


> See if this improves something.


*Notice*: Undefined variable: conn in */var/www/html/random.php* on line *23*

*Fatal error*: Uncaught Error: Call to a member function prepare() on null in /var/www/html/random.php:23 Stack trace: #0 {main} thrown in */var/www/html/random.php* on line *23*


----------



## axe0 (Jun 15, 2016)

My mistake.

```
const localhost = 'localhost';
const user = 'root';
const pass = '';
const db = 'db'; // fill in 
const table = 'test';

$time = date('Y-m-d');
$query = 'select * from '.table;

function random_pic($dir = 'flags/*.*') {
    $files = glob($dir);
    $file = array_rand($files);
    return $files[$file];
};
$img = random_pic();

$conn = new mysqli(localhost, user, pass, db);
$data = $conn->query($query);

if($data->num_rows == 0){
    $stmt = $conn->prepare('insert into '.table.' (image, storedDate) values(?, ?);');
    $stmt->bind_param('ss', $img, $time);
    if(!$stmt->execute()){
        echo "error:" . $stmt->error;
    }
    $stmt->close();
}

$data = $data->fetch_assoc();

if($data['storedDate'] != date('Y-m-d')){

    $stmt = $conn->prepare('update test set image = ?, storedDate = current_date;');
    $stmt->bind_param('s', $img);
    $stmt->execute();
    $stmt->close();
}
$conn->close();

// We'll need to query the db again to get fresh data 
$data = $conn->query($query)->fetch_assoc();

echo "<img src='$data[image]'>";
```


----------



## Brian07002 (Sep 15, 2011)

axe0 said:


> My mistake.
> 
> ```
> const localhost = 'localhost';
> ...


Still this error: *Notice*: Undefined variable: conn in */var/www/html/random.php* on line *23*

*Fatal error*: Uncaught Error: Call to a member function prepare() on null in /var/www/html/random.php:23 Stack trace: #0 {main} thrown in */var/www/html/random.php* on line *23*


----------



## axe0 (Jun 15, 2016)

What PHP version are you using?


----------



## Brian07002 (Sep 15, 2011)

axe0 said:


> What PHP version are you using?


*PHP Version 7.0.28-0ubuntu0.16.04.1*


----------



## Brian07002 (Sep 15, 2011)

Have any luck coming up with a solution?


----------



## axe0 (Jun 15, 2016)

axe0 said:


> My mistake.
> 
> ```
> const localhost = 'localhost';
> ...


I'm a bit stumbled why that error happens, if it was a different language like C# I would understand it. There's of course an easy fix which requires to violate the DRY, simply redefine $conn in the if statement.


----------



## Brian07002 (Sep 15, 2011)

axe0 said:


> I'm a bit stumbled why that error happens, if it was a different language like C# I would understand it. There's of course an easy fix which requires to violate the DRY, simply redefine $conn in the if statement.


Sorry, I just got in from work at 9:00pm (New York Time)

Maybe give it until Friday, and likely you will find the solution, it's a good day to figure things out like this...Sleep on it tonight, and by Friday, let your creativity flow into this script and you will likely find the solution. 

I could really use this script, as I am thinking that the idea of storing the image urls, the links AND doing the random bit all from mysql query would be the better option in terms over-all performance on the web server. Because as it stands currently, I am using the local directory to store the images and a long array (almost 200 links in the array) 

What do you think? Stick with what I am currently using, or hold off until you get this version?

Brian


----------



## axe0 (Jun 15, 2016)

A few hours of thinking is more than enough for this, I've dealt with db related issues for years. DB management are things that are typically globally needed, so a simple database class extending all mysqli features is something you probably want and hopefully fixes the problem.


```
const localhost = 'localhost';
const user = 'root';
const pass = '';
const db = 'db'; // fill in
const table = 'test';

class database extends mysqli{
    protected static $instance;

    public static function getInstance()
    {
        try{
            if(is_null(self::$instance)){
                self::$instance = new self(localhost, user, pass, db);
            }
        }
        catch (mysqli_sql_exception $exception){
            throw new mysqli_sql_exception($exception->getMessage());
        }

        return self::$instance;
    }

    public function perform($query)
    {
        $query = self::getInstance()->query($query)->fetch_assoc();

        return $query;
    }
}

function random_pic($dir = 'images/*.*') {
    $files = glob($dir);
    $file = array_rand($files);
    return $files[$file];
};

$time = date('Y-m-d');
$query = 'select * from '.table;

$img = random_pic();

$conn = database::getInstance();
$data = $conn->query($query);

if($data->num_rows == 0){
    $stmt = $conn->prepare('insert into '.table.' (image, storedDate) values(?, ?);');
    $stmt->bind_param('ss', $img, $time);
    if(!$stmt->execute()){
        echo "error:" . $stmt->error;
    }
    $stmt->close();
}

$data = $conn->perform($query);

if($data['storedDate'] != date('Y-m-d')){
    $stmt = $conn->prepare('update test set image = ?, storedDate = current_date;');
    $stmt->bind_param('s', $img);
    $stmt->execute();
    $stmt->close();
}

// We'll need to query the db again to get fresh data
$data = $conn->perform($query);

echo "<img src='$data[image]'>";
```


----------



## Corday (Mar 3, 2010)

axe0 said:


> A few hours of thinking is more than enough for this, I've dealt with db related issues for years. DB management are things that are typically globally needed, so a simple database class extending all mysqli features is something you probably want and hopefully fixes the problem.


Agree totally. Volunteer staff can only be expected to do so much on a particular problem. With info provided, OP can expand their thinking and advance towards a solution.


----------



## Brian07002 (Sep 15, 2011)

axe0 said:


> A few hours of thinking is more than enough for this, I've dealt with db related issues for years. DB management are things that are typically globally needed, so a simple database class extending all mysqli features is something you probably want and hopefully fixes the problem.
> 
> 
> ```
> ...


This code works as expected, can I ask for one more addition? I would like to link each image to it's own page. NOT linking all images to the same page. I am thinking this would work best if the links were store in the db, as I have 247 images/links.

Thank you so much for being a coder!
Excellent job!
Brian


----------



## axe0 (Jun 15, 2016)

Easy, add a parameter to the URL with the image as value, read the value of the parameter and done, no database connection required.

Links are not something you want stored in a database, if the link changes you have to update the database which puts unnecessary load to the site and links are the most easiest to change.


----------



## Brian07002 (Sep 15, 2011)

axe0 said:


> Easy, add a parameter to the URL with the image as value, read the value of the parameter and done, no database connection required.
> 
> Links are not something you want stored in a database, if the link changes you have to update the database which puts unnecessary load to the site and links are the most easiest to change.


I understand your coding ability is quite good, so your communication language is also quite good in terms of your coding, but I am not that good to just pickup up what you mean by add a parameter to the url with a value, I will leave that up to a professional like yourself...If you can do that for me, you can come to me as a reference for whenever the need may arise..

Thanks again!
Brian


----------



## axe0 (Jun 15, 2016)

URL parameter:
randomurl.com*-&nbspThis website is for sale!*-&nbspLoans Resources and Information.

Retrieving the parameter's value:
$_GET["parameter"]

I understand you're not very good in PHP, but from what I've been reading you were relying on me to get some code working for you which isn't how this part of the forum (should) work. Many forums like this are meant for either finding bugs (if you can't find it yourself) and pushing in the right direction or providing concepts how to get something done, but I believe I've done more than that which is why I didn't add any code in my previous reply, I wanted you to look into it so you could find out how it works. I mean, if someone would do the same, I would do some research in trying to find out what the heck they mean, try to find samples how what they mean work and try to implement it.

Having said that, if you want a URL with an image, all you need to do is make a link with a parameter, like:

```
<a href="index.php/?img=<?php echo $data['img'];?>">text</a>
```
Img will have everything you need, so to retrieve its value use $_GET variable like shown above.


----------

