1

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?

s1h4d0w
  • 762
  • 6
  • 27

2 Answers2

3

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.

ThiefMaster
  • 310,957
  • 84
  • 592
  • 636
  • Thanks, it works! I'm indeed a beginner, trying to learn PHP by Googling and experimenting. – s1h4d0w Apr 08 '14 at 22:47
  • Please be *very* careful. There is an incredible amount of **CRAP** (yes, bold uppercase crap) out there when you search for PHP tutorials and stuff. Especially if it's not very recent. To be honest, this is one of the main reasons (besides the language being much nicer) why I'd always recommend someone to learn Python instead of PHP. Anyway, virtual +1 for doing SQL the right way with prepared statements! – ThiefMaster Apr 08 '14 at 23:00
  • Thanks! I try to be as safe as possible and immediately use the right protection against SQL injection. I spend a lot of time researching the correct ways of implementing security and making sure no-one can mess with my code or database. Only thing I need to start doing is commenting my code :) – s1h4d0w Apr 09 '14 at 07:51
1

No need for the {}, try this:

 if ($rowmine['has'.$mine] == 0)
CMPS
  • 7,733
  • 4
  • 28
  • 53