davidnowlin Posted August 21, 2011 Share Posted August 21, 2011 Been scratching my head about this all day. Cannot figure it out. Any help would be appreciated. <?php $selectClause = 'SELECT * FROM idInfo WHERE'; $whereClause = ''; function addWhere($fxnName, $fxnValue) { if (!$whereClause) { return $fxnName . '=\'' . $fxnValue . '\''; } else { return ' AND ' . $fxnName . '=\'' . $fxnValue . '\''; } } $whereClause.=addWhere("firstName", $firstName); $whereClause.=addWhere("lastName", $lastName); $whereClause.=addWhere("idNum", $idNum); echo 'mysql_query("' . $selectClause . ' ' . $whereClause . '"); <br /><br />'; ?> This is meant to generate a query of the type: SELECT * FROM idInfo WHERE firstName='firstNameINPUT' AND lastName='lastNameINPUT' AND idNum='idNumINPUT' For some reason, though, the if statement always reads false. No matter how I try to work the syntax if (!$whereClause) if ($whereClause) if ($whereClause == NULL) if ($whereClause != NULL) if (empty($whereClause) etc. I've tried all of those and more, experimenting with and without quotes. They always return a FALSE for the existence of the variable, so that the string never contains the word "AND" as it should by the end. I've tried these same if statements outside the function and they work fine. Inside the function, it doesn't matter what the value of the variable is, the function runs as though it has no value. Comments? Suggestions? Quote Link to comment https://forums.phpfreaks.com/topic/245387-if-variable-nested-in-function-always-reads-null/ Share on other sites More sharing options...
AbraCadaver Posted August 21, 2011 Share Posted August 21, 2011 Probably better ways to go about it, but $whereClause is not available inside the function scope. Something like this maybe: function addWhere($fxnName, $fxnValue, $whereClause='') { $whereClause.=addWhere("firstName", $firstName, $whereClause); Quote Link to comment https://forums.phpfreaks.com/topic/245387-if-variable-nested-in-function-always-reads-null/#findComment-1260320 Share on other sites More sharing options...
davidnowlin Posted August 21, 2011 Author Share Posted August 21, 2011 Genius. Worked like a charm. Just had to set the variable as a parameter of the function. Thanks! By the way, making people answer questions about coding as part of the capcha for submitting questions about coding: also genius, and potentially hilarious. Quote Link to comment https://forums.phpfreaks.com/topic/245387-if-variable-nested-in-function-always-reads-null/#findComment-1260325 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.