Question

I have some code that doesn't seem to work. I'm using a form to post a value (green, blue, red, etc) and make it look up something in the database using that post value as part of a variable name.

$mine = 'green';

$querymine = $dbcon->prepare('SELECT * FROM mine WHERE playerid = :playerid');
$querymine->execute(array(
    'playerid' => $playerid
));
$rowmine = $querymine->fetch(PDO::FETCH_ASSOC);

if (${'rowmine[\'has'.$mine.'\']'} == 0) {
    header("location:mine.php");
    die();
}

It is looking up the column "hasgreen", which is INT 4 in this case. The problem is, it tells me that $rowmine['hasgreen'] is NULL, thus I'm getting kicked back to "mine.php". I'm not sure what the problem is, maybe the use of \' in the variablename?

Was it helpful?

Solution

You have an array. There is no reason to use a variable variable here.
You can simply use $rowmine['has'.$mine] instead!

Since you are probably a beginner: If you use variable variables you should always consider using an array instead. Variable variables are a great way to get unreadable spaghetti code.

OTHER TIPS

No need for the {}, try this:

 if ($rowmine['has'.$mine] == 0)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top