We all make rookie mistakes, especially as rookies. In an act of humility, DJ sent us some PHP she wrote at the tender age of 19.
From the submission,
I recently ran across some code I wrote on my first project for a new company I'd just started working for. Part of the site required I show some content picked at random from a database. Since I'd only been doing PHP for about 6 months I was blissfully unaware of the array_rand function so I wrote this instead.
// Create an array of all the ID's used
$int = array();
$query = $sql->query("SELECT * FROM table");
while($row = $sql->objects('',$query)) {
$int[ $row->id ] = $row->id;
if ($row->id > $max) {
$max = $row->id;
}
}
// Find a random ID that has been used
$x = false;
while ($x == false) {
$rand = rand(0,$max);
foreach ($int as $thing) {
if ($thing == $rand) {
$x = true;
}
}
}
// Get a row by random ID
$query = $sql->query("SELECT * FROM table where id=".$rand);
I can only imagine what the code looks like since she's discovered array_rand but I didn't have the heart to tell her about SELECT * FROM table ORDER BY RANDOM() LIMIT 1 or the variants thereof.