dimanche 16 avril 2017

Create a randomized assoc array from database table results

I am creating a simple drag and drop jquery game and it requires a shuffled resultset of 10 rows from my database table. I am able to achieve this by repeating 10 separate blocks of queries, but I am sure there must be a more elegant way to do this. I tried many things, with loops and append etc. but I can't get the loop-way working.

I can't get this loop version to work:

<script type="text/javascript">
<?php
// first create list of 10 fake id's and shuffle them
$id_array = range(0, 9);
shuffle($id_array);

/*
    // then loop to fetch all data from MySql table with spanish, english
    // CANNOT GET THIS WORKiNG ?
    for (i = 0; i < 10; i++) {
        $query = "SELECT id, english, spanish FROM colors WHERE id = $id_array[i]";
        $result = mysqli_query($link, $query);
        $row = mysqli_fetch_array($result);
        $rand_value.append(i) = $row['english'];
        $name.append(i) = strtoupper($row['spanish']);
    }
*/

Writing it out works, but there must be an easier way...

<script type="text/javascript">
<?php
// create all input from MySql table for drag and drop area with spanish, english
$query = "SELECT id, english, spanish FROM colors WHERE id = $id_array[0]";
$result = mysqli_query($link, $query);
$row = mysqli_fetch_array($result);
$random_key0 = $row['id'];
$rand_value0 = $row['english'];
$name0 = strtoupper($row['spanish']);

$query = "SELECT id, english, spanish FROM colors WHERE id = $id_array[1]";
$result = mysqli_query($link, $query);
$row = mysqli_fetch_array($result);
$random_key1 = $row['id'];
$rand_value1 = $row['english'];
$name1 = strtoupper($row['spanish']);  

// and so on to run 10 queries total
?>




Aucun commentaire:

Enregistrer un commentaire