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?

有帮助吗?

解决方案

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.

其他提示

No need for the {}, try this:

 if ($rowmine['has'.$mine] == 0)
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top