PHP function for form not working - php

Why is this php function not working? It does work when not using $element.
With $element it always returns test.
function setVar($element)
{
if(isset($_POST['$element'])){
$varname = $_POST['$element'];
}
else {
$varname = 'test';
}
return $varname;
}
$var = setVar('element_6');

You probably mean:
... $_POST[$element] ...
without the quotes? Single-quoted content never gets replaced.

Change $_POST['$element'] in your code to $_POST[$element] and it should work fine.. $_POST['$element']) refers to nothing right now.

You'll need to change $_POST['$element'] to $_POST[$element]. Anything between single quotes is treated literally.
See: http://php.net/manual/en/language.types.string.php

You're referencing $_POST['$element']. Note that the single quotes around $element here turn it into a static string.
Solution: Remove the quote marks, and it will parse the $element properly.

Related

Laravel Quick Question : $data->Day(variable here) how to use variable on this? [duplicate]

How can i reference a class property knowing only a string?
class Foo
{
public $bar;
public function TestFoobar()
{
$this->foobar('bar');
}
public function foobar($string)
{
echo $this->$$string; //doesn't work
}
}
what is the correct way to eval the string?
You only need to use one $ when referencing an object's member variable using a string variable.
echo $this->$string;
If you want to use a property value for obtaining the name of a property, you need to use "{" brackets:
$this->{$this->myvar} = $value;
Even if they're objects, they work:
$this->{$this->myobjname}->somemethod();
As the others have mentioned, $this->$string should do the trick.
However, this
$this->$$string;
will actually evaluate string, and evaluate again the result of that.
$foo = 'bar';
$bar = 'foobar';
echo $$foo; //-> $'bar' -> 'foobar'
you were very close. you just added 1 extra $ sign.
public function foobar($string)
{
echo $this->$string; //will work
}
echo $this->$string; //should work
You only need $$string when accessing a local variable having only its name stored in a string. Since normally in a class you access it like $obj->property, you only need to add one $.
To remember the exact syntax, take in mind that you use a $ more than you normally use. As you use $object->property to access an object property, then the dynamic access is done with $object->$property_name.

What do braces surrounding a member variable mean in PHP?

I am wondering what { } in the following. What { } is doing here? $this->{$key} = $value;
Thanks in advance.
In one file
$config['field']['calendar'] = array('type'=>'boolean');
$config['field']['category'] = array('type'=>'boolean');
$config['field']['customers'] = array('type'=>'boolean');
...
$this->preference_form->initalize($config);
And in Preference_form.php
function initalize($config = array())
{
foreach($config as $key => $value)
{
$this->{$key} = $value;
}
}
They're optional in this case, but it's a way of making it clearer to the reader (and the parser) that you're referring to a variable.
http://www.php.net/manual/en/language.variables.variable.php
In order to use variable variables with arrays, you have to resolve an
ambiguity problem. That is, if you write $$a[1] then the parser needs
to know if you meant to use $a[1] as a variable, or if you wanted $$a
as the variable and then the [1] index from that variable. The syntax
for resolving this ambiguity is: ${$a[1]} for the first case and
${$a}[1] for the second.
Another case where this syntax is useful is when expanding a function call in a string.
This doesn't work (or rather it'll evaluate $someObj as a string, and then append ->someFunc():
$myString = "$someObj->someFunc()";
But this does what you'd expect:
$myString = "{$someObj->someFunc()}";
It's escaping the variable expression so that the member can be set dynamically.
Take a look at the documentation here: http://php.net/manual/en/language.types.string.php#language.types.string.parsing.complex

PHP not sending id

I have a script that I wrote to look up an ID based on uniqueID
if ($_REQUEST['uniqueId'] != ""){
$qA = "SELECT id FROM customerdata WHERE uniqueId = \"". $_REQUEST['uniqueId']."\"";
$rA = mysql_query($qA);
list($id) = mysql_fetch_row($rA);
echo $id;
exit;
if ( mysql_num_rows ($rA) > 0) {
header('Location:response-en.php?id=$id');
}
else
{
header('Location:not-found.php');
}
}
Rather than sending the user to response-en.php?id=1 it sends them to response-en.php?id=$id
Any idea why this is happening? Any help would be greatly appreciated! Thank you!
Use:
header('Location:response-en.php?id='.$id);
When you use a single quote: '
This is a string literal. Everything (and I mean EVERYTHING) inside that string is taken wholesale. If you did this: $something = 'Location:response-en.php?id=$id';, the value of $something is: Location:response-en.php?id=$id In order to add a variable into the string, you use the concatenation operator .. Thus, the value of $something after $something = 'Location:response-en.php?id='.$id; would be Location:response-en.php?id=5 (assuming $id = 5)
See: http://www.php.net/manual/en/language.types.string.php#language.types.string.syntax.single
When you use double quote: "
PHP will search inside your sting to find any variables. It will then replace the variable name with the value of the variable. If you did this: $something = "Location:response-en.php?id=$id";, the value of $something is: Location:response-en.php?id=5 - note the use of double quotes.
See: http://www.php.net/manual/en/language.types.string.php#language.types.string.syntax.double
Also, I wanted to add that your script is vulnerable to SQL-injection attack. Always sanitize query-string values before using them in an SQL query. For more info on sanitizing values for sql, see the docs for mysql_real_escape_string.
Variables inside a single-quoted string are not parsed. Variables inside double quotes are. Check out:
http://www.php.net/manual/en/language.types.string.php
You need double quotes to process variables in a string. Not single quotes.
You have to use " in stead of '
header("Location:response-en.php?id=$id");
or:
header('Location:response-en.php?id='.$id);
Try enclosing your string with double quotes instead of single quotes for correct variable parsing:
"Location:response-en.php?id=$id"
or use complex syntax with curly braces surrounding your variables:
"Location:response-en.php?id={$id}"
See manual.

Variable inside double quotes in PHP array keys

I've something weird into my code and I really don't get the behavior.
I always used array with string variables keys like this:
$string = "my key";
$array[$string] = "my value";
But in one case, it doesn't work. I'm forced to put $string into double quotes, otherwise my array remains empty.
I really don't understand why. Moreover, further in my code I use the same "$string" as an id to create an another array, and it works fine without double quotes.
Here is my code where double quotes are needed (array[]):
foreach($xml2->menu as $children) {
$id = $children['id'];
$this->array["$id"] = $children->label;//Problem here
}
And here, the code without double quotes ($resultArray[]):
for($i=0; $i < count($idArray); $i++){
$id = $idArray[$i];
$resultArray[$id] = $this->array[$id];//Problem here
}
Does someone have any idea about why this is happening?
Edit:
The content of $idArray[$i] and $children[$id] is some string like "about", "contact" etc.
And when I say "it doesn't work", I mean that the created array is null.
Does $children["id"] contain an object? Then type it to an int:
$id = (int) $children["id"];
Then you can use it again as $id.

My PHP Function isn't working

I'm having trouble with the following code. What it should do is echo cats.php followed by example.php but it's not echoing the example.php. Any ideas why this might be happening?
$bookLocations = array(
'example.php',
'cats.php',
'dogs.php',
'fires.php',
'monkeys.php',
'birds.php',
);
echo $bookLocations[1];
function findfile($filenumber)
{
echo $bookLocations["$filenumber"];
}
findfile(0);
Try changing,
echo $bookLocations["$filenumber"];
to:
echo $bookLocations[$filenumber];
Edit* To expand on Thomas's correct answer, instead of using global variables, you could change your method to:
function findfile($filenumber, $bookLocations)
{
echo $bookLocations[$filenumber];
}
i believe you may also need to declare the global variable in your function.
global $bookLocations;
Ok, there are two issues.
Variable Scope
Your function doesn't know the array $bookLocations, you need to pass it to your function like so:
function findfile($filenumber, $bookLocations)
Array key
You don't want to wrap your array key in quotes:
wrong: $bookLocations["$filenumber"];
right: $bookLocations[$filenumber];
The quotes in "$filenumber" turn your key into a string, when the keys to your array are all numbers. You are trying to access $bookLocations["1"] when in fact you want to access $bookLocations[1] -- that is to say, 1 is not the same as "1". Therefore, like others have said, you need to get rid of the quotation marks around the key (and check your variable scope too).
function findfile($filenumber)
{
global $bookLocations;
echo $bookLocations[$filenumber];
}
Good-style developers usually avoid global variables. Instead, pass the array to the function as the parameter:
function findfile($files, $filenum)
{
echo $files[$filenum];
}
$bookLocations is out of scope for your function. If you echo $filenumber you will see that it's in scope because you passed it in by value. However, there is no reference to $bookoLocations.
You should pass in $bookLocations
declaration: function findfile($filenumber, $bookLocations){
call: findfile(1, $bookLocations);
You could also to declare $bookLocations as global, but globals should be avoided if possible.

Categories