Reputation: 6615
I would like to know if there is an easier way to assign all my different columns to a variable. I have over 70 to check if a user has earned a specific song. This is a shortened version of the code. I haven't done all the songs yet and I was wondering if there is an easier way.
$results = mysqli_query($con,"Select * FROM users WHERE user_name ='$username'");
while ($row = mysqli_fetch_array($results))
{
$userpoints = $row['points'];
$intro = $row['intro'];
$fightingfires = $row['fightingfires'];
$may = $row['may'];
$crowdedstreet = $row['crowdedstreet'];
}
Upvotes: 1
Views: 3343
Reputation: 46900
It's as simple as doing
extract($row);
Your loop will look something like
while ($row = mysqli_fetch_array($results))
{
extract($row);
echo $intro;
}
Upvotes: 1
Reputation: 84
Yup, use php extract() http://php.net/manual/en/function.extract.php
Here is a simple example:
$results = mysqli_query($con,"Select * FROM users WHERE user_name ='$username'");
while ($row = mysqli_fetch_array($results))
{
extract($row);
}
// This will give you variables for each item
// so you will get $points for what would have been $row['points'], etc.
Upvotes: 6
Reputation: 4024
Edit: Look at the other people's examples on using extract()
which does similar stuff to the foreach loop that I have here:
Try using variable variables:
while ($row = mysqli_fetch_array($results))
{
foreach ($row as $column => $value) {
$$column = $value;
}
}
For each row, essentially you'll be loading variables that have the same name as the column name. It would be like doing:
$points = $row['points'];
$intro = $row['intro'];
$fightingfires= $row['fightingfires'];
$may = $row['may'];
$crowdedstreet= $row['crowdedstreet'];
..etc
Basically, "points" is the name of the first key, and the variable gets the name "points" so you get variable $points
.
http://php.net/manual/en/language.variables.variable.php
Upvotes: 2