Hi, I'm trying to figure out how to create a random integer, that I can ALSO control by using links, which I'm setting as buttons.
In short, I've been programming an MP3 Player.

Currently, I have "$playing" set as a random integer, but I want links to increase by 1, -1, and random on click.

$result = mysql_query("SELECT * FROM songlist");
$tracks = mysql_num_rows($result);
$playing =rand(1,$tracks);

My play button currently just reloads the current page (<A HREF="">) to select another random track.
But obviously, I still get the same song sometimes, but that's a lower concern.

I'm just wanting to know how to have a randomly generated number on load, that can be increased and decreased by clicking images.

When I tried to link <A OnClick=> to a javascript function to increase it, it still loaded up only the $playing variable declared above, near the top.
Of course, I barely know javascript, so I may have likely been doing something wrong.

Could someone please help me out here?

It would probably help us get a better idea of how to help you if we saw the rest of your code relevant to your problem.

I am a little confused.

If you want a random integer, why would you want to increment / decrement it by one to select the next track? Surely, you'd want another random track?

Anyway, you could:

$result = mysql_query('SELECT COUNT(*) AS `count` FROM songlist');
$count = mysql_fetch_assoc($result);

// Find random, current track. Then find previous (or first) and next (or last) tracks
$current = isset($_GET['track']) ? (int) $_GET['track'] : rand(1, $count);
$previous = max(1, $current - 1);
$next = min($count, $current + 1);

// Output
<a href="play?track=<?php echo $previous; ?>" title="Previous">Previous</a>
<a href="play?track=<?php echo $next; ?>" title="Next">Next</a>

Thanks... I've got to run into town, but I'l try your code later, unless you update.

The reason I want a random integer, is because I reference the songs by IDs.
When the player loads, I want it to START at a random track, so it's not ALWAYS the same thing when you visit.

I want the Next/Prev track, so visitors can go back and forth between the songs (by ID), in case one gives them a headache or something. :3

Full Code (Still needs to be cleaned up, because I just edited it from a download section with a counter, lol...)

<?php
// Error reporting:
error_reporting(E_ALL^E_NOTICE);

// Including the DB connection file:
require 'remix/archive/connect.php';

$extension='';
$files_array = array();
$root="./remix/archive";
$result = mysql_query("SELECT * FROM remix");
$tracks = mysql_num_rows($result);

$playing =(rand(1,$tracks));

/* Opening the thumbnail directory and looping through all the thumbs: */

$dir_handle = @opendir($root) or die("There is an error with your file directory!");

while ($file = readdir($dir_handle))
{
/* Skipping the system files: */
if($file{0}=='.') continue;
/* Line 20 */
/* end() returns the last element of the array generated by the explode() function: */
$extension = strtolower(end(explode('.',$file)));

/* Skipping the php files: */
if($extension == 'php') continue;

$files_array[]=$file;
}

/* Line 30: Sorting the files alphabetically */
sort($files_array,SORT_STRING);

$file_downloads=array();

$playing = mysql_query("SELECT * FROM songlist WHERE ID=$playing");

if(mysql_num_rows($playing))
while($row=mysql_fetch_assoc($playing))
{
/* Line 40: The key of the $file_downloads array will be the name of the file,
and will contain the number of downloads: */

echo'<DIV ID=playerdiv><TABLE ID=player><TR><TD ROWSPAN=3 WIDTH=30 ID=buttons><A HREF=""><IMG SRC=/playc.jpg HEIGHT=32 ALT=Next></A><HR>
<A HREF=/player_stop.php><IMG SRC=/stopa.png HEIGHT=32 ALT=Stop>
<TD ROWSPAN=2 ID=playing><FONT SIZE=-1><I>Playing:</I></FONT><BR><CENTER><a ID=song href="remix/archive/download.php?file='.$row['filename'].'">'.$row['song'].'</A>
<TH>'.$row['style'].' Mix<TR><TD>Author: '.$row['author'];
/*line 50 */
echo '<EMBED src="remix/archive/'.$row['filename'].'" hidden=true autostart=true loop=true>
<TR><TD ID=footer COLSPAN=2><FONT SIZE=-2><CENTER>Game: '.$row['origin'].' | System: '.$row['originS'].'</TABLE>



</DIV>';
}?>

Thanks! :D

Update: Decided to try it before heading out, and got it adapted for my setup... thanks alot, works like a charm! :D
Now, could I ask how to get the last track to loop to track 1, and vice versa?

Member Avatar for diafol

Here's some random bit of code I had that I refactored for your use. It's raw and uses $_SESSION variables directly, so not brilliant, but may give you an idea about -1/+1

<?php
    session_start();
    //for testing purposes
    //unset($_SESSION['linear']);
    //unset($_SESSION['random']);
    if(!isset($_SESSION['linear'])){
        /*$r = mysql_query("SELECT id FROM songlist ORDER BY id");
        while($d=mysql_fetch_array($r)){
            $linear[] = $d['id'];   
        }*/
        $_SESSION['linear'] = array(41,46,67,114,345,367,766,811,956); //hard-coded for example
    }

    if(isset($_GET['id']) && in_array($_GET['id'],$_SESSION['linear'])){
        $current = $_GET['id'];
    }else{
        $current = $_SESSION['linear'][0];  //default
    }   

    $pos = array_search($current,$_SESSION['linear']);

    if($pos == 0){
        $prev = false;
        $next = $_SESSION['linear'][$pos + 1];  
    }elseif($pos == count($_SESSION['linear'])-1){
        $next = false;
        $prev = $_SESSION['linear'][$pos-1];    
    }else{
        $next = $_SESSION['linear'][$pos+1];
        $prev = $_SESSION['linear'][$pos-1];
    }

    if(!isset($_SESSION['random']) || (isset($_SESSION['random']) && count($_SESSION['random']) < 2)){
        $_SESSION['random'] = $_SESSION['linear'];
        shuffle($_SESSION['random']);
    }

    $random = array_values(array_diff($_SESSION['random'], array($current)));
    $_SESSION['random'] = $random;
    $rnd = $random[0];

    /*$r = mysql_query("SELECT * FROM songlist WHERE id = $current");
    $d = mysql_fetch_assoc($r);
    $mp3code = ...;*/

    echo "LINEAR: ";
    print_r($_SESSION['linear']);
    echo "<br />RANDOM: ";
    print_r($_SESSION['random']);
    echo "<br />";

    $button = ($prev) ? "<a href=\"?id=$prev\"><button>Prev</button></a>" : "<button disabled=\"disabled\">Prev</button>";
    $button .= " <a href=\"?id=$rnd\"><button>Random</button></a>";
    $button .= ($next) ? "<a href=\"?id=$next\"><button>Next</button></a>" : "<button disabled=\"disabled\">Next</button>";
    echo $button;
?>

Thanks... I wasn't simply looking for a handout, I like to mess around with code to understand it :3
Basically, I usually learn best by hands on, messing with complex things... Surprised I haven't blown up yet! :P

I appreciate the help, all my PHP knowledge has been from editing, so didn't know how to create an inline value change properly...

But looking at your post, even though I'm in a rush, I seem to be having a brainfart when trying to figure out how to set a loop for the last song($tracks) to cycle with 1...?

Maybe settings something like "if id=$tracks {next=1}?
But then, couldn't something like that have bugs, and be more long-winded?
Would there be a better way?

Thanks again!

Member Avatar for diafol

Sorry, didn't mean to give a complete solution, just an idea of carrying data through sessions. My idea was that you keep a linear array of all your song ids (which doesn't change on button click). There is a random array which just shuffles the linear array of ids. Everytime a song is chosen that is in the random array, it gets taken out of that array, so you don't get the same song playing 4 times in a row. When the random array is depleted it gets replenished with a new shuffle of the linear array.

There are plenty of ways to do this BTW, this was just some old code I had kicking around for another purpose. I thought of a ?id=prev, ?id=next, ?id=rnd etc but that would mean a lot more refactoring of the code I already had.

I've commented the code, so hopefully, you'll get a better understanding of what's going on:

<?php
    //THE session_start() IS A MUST - has to be on every page or the session will be lost
    session_start();

    //for testing purposes - uncomment these lines to reset the session arrays
    //unset($_SESSION['linear']);
    //unset($_SESSION['random']);

    if(!isset($_SESSION['linear'])){
        //UNCOMMENT this to use your DB - you'll need your connection details of course
        //COMMENT OUT THE hard-coded line

        /*$r = mysql_query("SELECT id FROM songlist ORDER BY id");
        while($d=mysql_fetch_array($r)){
            $linear[] = $d['id'];   
        }*/

        $_SESSION['linear'] = array(41,46,67,114,345,367,766,811,956); //hard-coded for example
    }

    //THIS CHECKS FOR THE 'id' IN THE URL and makes that 'id' the current song to play
    //If it doesn't exist, e.g. user types in some random junk, then the default song is chosen
    if(isset($_GET['id']) && in_array($_GET['id'],$_SESSION['linear'])){
        $current = $_GET['id'];
    }else{
        $current = $_SESSION['linear'][0];  //default
    }

    //GET the array index for the current song and set the prev/next button song ids  
    $pos = array_search($current,$_SESSION['linear']);
    if($pos == 0){
        $prev = false;
        $next = $_SESSION['linear'][$pos + 1];  
    }elseif($pos == count($_SESSION['linear'])-1){
        $next = false;
        $prev = $_SESSION['linear'][$pos-1];    
    }else{
        $next = $_SESSION['linear'][$pos+1];
        $prev = $_SESSION['linear'][$pos-1];
    }

    //CREATE the random array if it doesn't exist or if it is depleted
    if(!isset($_SESSION['random']) || (isset($_SESSION['random']) && count($_SESSION['random']) < 2)){
        $_SESSION['random'] = $_SESSION['linear'];
        shuffle($_SESSION['random']);
    }

    //remove the current song from the random array and reset indexes
    $random = array_values(array_diff($_SESSION['random'], array($current)));
    $_SESSION['random'] = $random;

    //select the first song in the random array as the random button id
    $rnd = $random[0];

    //UNCOMMENT THIS to get the MP3 details of the current song
    /*$r = mysql_query("SELECT * FROM songlist WHERE id = $current");
    $d = mysql_fetch_assoc($r);
    $mp3code = ...;*/

    //JUST DEBUGGING STUFF TO SHOW the content of the linear and random arrays
    echo "LINEAR: ";
    print_r($_SESSION['linear']);
    echo "<br />RANDOM: ";
    print_r($_SESSION['random']);
    echo "<br />";

    //BUILD THE buttons
    $button = ($prev) ? "<a href=\"?id=$prev\"><button>Prev</button></a>" : "<button disabled=\"disabled\">Prev</button>";
    $button .= " <a href=\"?id=$rnd\"><button>Random</button></a>";
    $button .= ($next) ? "<a href=\"?id=$next\"><button>Next</button></a>" : "<button disabled=\"disabled\">Next</button>";

    //PRINT THE buttons - this should go in the html body somewhere
    echo $button;
?>

Thanks! I didn't mean that you gave the complete solution, or was I complaining: I was just stating that I was thankful for the general example, so I could decode it, because I'm not like many people who just want a handout.

I'll look over the code later, it's kinda long, and it's getting late, lol. But thanks again!
I'm so thankful, that I'd PM you a paypal donation, but your sig says you don't like that, so...
Lol, jk, but thanks for the time you spent helping! :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.