how to use a PHP Constant that gets pulled from a database - php

Can you read out the name of a PHP constant from a database and use it inside of a php variable, to display the value of the constant for use in a menu?
For example here's what I'm trying to accomplish
In SQL: select menu_name AS php_CONSTANT where menu_id=1 the value returned would be L_HOME which is the name of a CONSTANT in a php config page. The php config page looks like this define('L_HOME','Home'); and gets loaded before the database call.
The php usage would be $db_returned_constant which has a value of L_HOME that came from the db call, then I would place this into a string such as $string = '<ul><li>' . $db_returned_constant . '</li></ul>' and thus return a string that looks like $string = '<ul><li>Home</li></ul>'.
To sum up what I'm trying to do
Load a config file based on the language preference
query the db to return the menu name, which is the name of a CONSTANT in the config file loaded in step one, and also retrieve the menu_link which is used in the "onclick" event.
Use a php variable to hold the name of the CONSTANT
Place the variable into a string that gets echo'd out to create the menu displaying the value of the CONSTANT.
I hope this makes enough sense...is it even possible to use a constant like this?
Thanks.

define('L_HOME','Home');
$db_returned_constant = 'L_HOME'; // value actually retrieved from db
echo constant($db_returned_constant);
// will output 'Home'

Sure, just retrieve the name of a constant into a string and then use constant.

Related

Create session variable from mysql column parameter

I am trying to create a php session variable which should reference "language":"ENG" (and more specifically ENG) within the table column params.
Example: Originally I've been using a "userLanguage" column and created my php session variable like this:
$_SESSION['userLanguage'] = $result[0]['userLanguage'];
Since "language":"ENG" is only one part of the field's value ({"admin_style":"","admin_language":"","language":"ENG","editor":"","helpsite":"","timezone":""}), this obv. doesn't work anymore. Is there an easy way to pull ENG from language? Help would be much appreciated.
Simply run a json_decode() on the field value.
$params = json_decode($result[0]['params']);
if(isset($params->language)){
$_SESSION['userLanguage'] = $params->language;
}

Calling a variable by passing variable name as a string

I've got a list of variables. Let's call it a=1,b=2,c=3. I would like to pass the variable name to a function as a string and then retrieve its' value. Is there a way to achieve this in PHP? I', hoping to use this in page object pattern with Gherkin to pass a variable name to a gherkin step.
I was able to resolve the problem by using ${$arg} notation as described by #waterloomatt above.

getting the count value in PHP using value command

I am making a dashboard using php and displaying it on webpage using html. For this I am taking some count values. Is !$value[" variable"] valid in php? How do i get the not of (!=) value? There is no other way to get the data. I am getting the values from a database.
print "<td><a href=\"$strBase and status!='Closed'\" target=\"_blank\">".$value[" ? "]."</td>";
I need to print !closed. Somehow I do not know how to pass that inside $value[].
If you want to use a variable as a key in order to retrieve a value from an array you can do as follows (I use a snippet of your code):
.$value[$myVar].
Where $myVar should be a string with the name of the key you want to retreive from $value
But anyhow, your question is pretty unclear so I'm not sure if this is what you are looking for.
You can check if the variable is empty(), i.e.:
if(empty($value["variable"])){
echo "variable is empty";
}

Using a php variable inside an sql query

In my php script,i am using a php variable inside an sql query.The php variable acquires its value through a post variable as follows:
$desc0=$_POST['desc0'];
$desc1=$_POST['desc1'];
$desc2=$_POST['desc2'];
$desc3=$_POST['desc3'];
$desc4=$_POST['desc4'];
$desc5=$_POST['desc5'];
$desc6=$_POST['desc6'];
$desc7=$_POST['desc7'];
$desc8=$_POST['desc8'];
$desc9=$_POST['desc9'];
The query is:
for($i=0;$i<10;$i++)
{
$q="insert into photos(name,category,description) values ('{$name{$i}}','$category','{$desc{$i}}')";
}
The problem is that on submitting the form i am getting an error which says
"undefined variable desc".
Therefore its not taking the values from the previously defined variables?
Any help?
First of, you code is completely unsafe - you should not pass user data directly into your query. There are many topics about it, and this is a good start.
Next, you don't need to store your data in such weird way. What if you'll want to pass 20 photos? In HTML, name your fields like photos[] - and in PHP, your values will be correctly parsed as an array $_POST['photos'], so you will be able to work with array:
$photos = $_POST['photos'];
foreach($photos as $photo)
{
//$photo contains certain item, so handle it with your logic
}
Finally, your issue is because of non-obvious PHP possibility for array-dereference with curly brackets. So your $desc{$i} is an attempt to access $i-th index for non-existent array $desc. Either use $desc$i or use concatenation to separate your variables.
You must change $desc{$i} to ${"desc" . $i}

PHP eval() function

The PHP function eval() appears to be a rather interesting function. Can someone explain why it works in this given situaton, on line: 14
function Parse($inFrontEnd)
{
// Now create an array holding translation tokens with some from above
// Load translation table into buffer
$tableLines = file(Utilities::GetRelativePath(TTABLE_DIR).TTABLE); // Array of lines from TTable.cfg
// Explode by whitespace
foreach($tableLines as $aLine)
{
$lineParts = EXPLODE(' ', $aLine);
$word = "/".$lineParts[0]."/";
$definition = $lineParts[1];
// Add key (word) => value (definition) to array
// Eval() to return value of the const
Main::$translateChars[$word] = eval("return $definition;");
}
// Read data from template file
$parseArray = file($inFrontEnd); // Load FrontEnd source code into array ready for parse
/* Perform the translation of template by the translation table defined data */
$parseArray = preg_replace(array_keys(Main::$translateChars), array_values(Main::$translateChars), $parseArray);
return $parseArray;
}
So what I'm doing here is reading in a template from a template directory. The templatename.php file comprises of text tokens written constant-like, which are then translated by regular expressions replacing the tokens with the data the constants with their names hold, thus returning a fully validated page of a webpage, which is printed for the user to view. This allows pages to be very dynamic by allowing the reuse of these tokens over many webpages (templates).
My question is: I had trouble for a while with the line that uses eval(). What I'm trying to do there is fill an array with each key being the name of the constant read in from, what I've named, the translation table (TTable.cfg), which holds the name of each token and the constant associated with it:
TITLE TITLE
CSS_INCLUDE CSS_INCLUDE
SHOW_ALL_POSTS SHOW_ALL_POSTS
...
So with the protocol [TOKEN] [CONSTANT][CR][LF]
The keys within the array would be created fine, but the values would return null or break my code when I had the key be associated with: constant($definition);
It complained it couldn't find the constants being declared. However, when I use eval as is on this line, each key associated with: eval("return $definition;");
it works as I want it - the values as their corresponding constant's data.
I do apologise for the length of this post. I couldn't find any other example for my question other than the case I found it in.
The value of the variable $definition is replaced into the string definition "return $definition;", as you're using double quotes. Hence, what is passed to eval is essential something like this: "return FOO;", where FOO is the value of the variable $definition.
Now, that code is evaluated using eval(), and the result is returned as the result of the evaluation, which is the value of the constant FOO (different in each iteration).
Using the constant in this case makes more sense: It is faster, potentially securer, and more readable.
if ( defined( $definition ) ) {
$constval = constant( $definition );
}
else {
$constval = $definition;
}
This will also give you some insight of why it works when using eval() and not just constant(); PHP replaces unknown constants with their respective names, thus eval works in your case. However, any other way would raise warnings and be a bad practice, as it doesn't make clear what's going on to the reader.
Remember, eval is evil, so don't use it, when you can avoid it. Here you could just use constant instead.
The tiniest of oversights. I forgot to clean $definition after I exploded it from each line of the translation table. So a simple trim() has solved the problem.
constant($definition);
Now works.
Crazy :D

Categories