Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Casting PHP into an array and looping through

Tags:

php

I am working on an application for our karate school and would like to get the technique names from the database, store them in an array in a random order and be able to click a button to move through the entire array one at a time.

I have thought about this in several different ways including just doing it randomly from the database which was pretty easy, but it pulls the same technique multiple times and I only want it done once.

Sample code below lists them all randomly just like it should and when I refresh the browser it creates a new list just like I want. Now I would like to know how I could display only one at a time and keep it in the browser until all of them have been gone through.

$sqlQuery= "Select * from Techniques Order BY Rand()";
$statement = $db->prepare($sqlQuery);
$statement->execute();
while($row = $statement->fetch(PDO::FETCH_ASSOC)):
    $techniqueName = $row['Technique_name'];
?>
    <ul>
    <li><?php echo $techniqueName; ?></li>
    </ul>
<?php endwhile; ?>

I really have no idea if this makes any sense. I would also like to stay away from javascript if possible, although that is not really a requirement. Basically it is a fun little game idea that would allow the students to practice without doing the same technique a bunch of times and missing other ones.

Any thoughts would be much appreciated.

like image 884
D.j. Dimick Avatar asked Oct 17 '22 15:10

D.j. Dimick


1 Answers

If you want to "stay away from javascript" you can save the values in an array, which is stored in a session. On a reload the array in the session is read and one random value is popped from it. At each request the array in the session gets smaller until the array is empty. Then you can reload a new set of techniques from the database. The source code could look like this:

<?php
session_start();
if (!isset($_SESSION['data'])) {
    /*
     * Access the database here. For testing purposes
     * create a dummy array instead
     */
    $array = range(1, 10);
    shuffle($array);
    $_SESSION['data'] = $array;
}
$value = array_pop($_SESSION['data']);
if (!count($_SESSION['data'])) {
    // array is empty, delete it so a new one gets created on the next request
    unset($_SESSION['data']);
}

echo "The current value is: ".$value."<br />\n";

// only for debugging:
if (isset($_SESSION['data'])) {
    var_dump($_SESSION['data']);
} else {
    echo "No array in 'data' set\n";
}

If you want to use javascript you can load all the values in a javascript array. Then you use javascript to iterate over the array and display the value you want until you reached the end. After that you can send a new request to get a new set of techniques from the database.

like image 90
Progman Avatar answered Oct 30 '22 04:10

Progman