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?

0

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks, it works! I'm indeed a beginner, trying to learn PHP by Googling and experimenting.
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!
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 :)
1

No need for the {}, try this:

 if ($rowmine['has'.$mine] == 0)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.