PHP Dynamic Variables

Let's say that you have a bunch of data in a recordset and you want to populate that data into a list of variables. In my example we will draw 20 items from a players inventory from a MySQL table which stores all the items for a player in rows we call slot_1, slot_2, slot_3, … all the way to 20. So when we pull all of the items from the MySQL table we want to assign them to variables respectively. For example, our variable of "slot_1" that we are creating will equal "slot_1" from the MySQL table.

<?php
//the recordset
mysql_select_db($database_connect, $connect);
$query_Recordset1 = sprintf("SELECT * FROM inventory WHERE player_id='1'");
$Recordset1 = mysql_query($query_Recordset1, $connect) or die(mysql_error());
$row_Recordset1 = mysql_fetch_assoc($Recordset1);
$totalRows_Recordset1 = mysql_num_rows($Recordset1);
 
//Loop and assign the variables accordingly
$i=1; do {
${"slot_{$i}"} = $row_Recordset1['slot_'.$i];
$i++;} while ($i<=20);
?>

Tags: