i wrote the following code...
<?php
$conn=mysql_connect("localhost","","");
if($conn)
echo "connection established";
mysql_select_db("moviesite");
$que="select * from movie";
$result=mysql_query($que,$conn);
?>
<html>
<title>movie database</title>
<body>
<table border=1 align=center>
<th colspan=2>
PEOPLE<a href='movie.php?action=add & id='>[ADD]</a>
</th>
<?php
$ta_row=<<<eod
<tr>
<td>
$mov_name
</td>
<td>
<a href='movie.php?action=edit & id=$mov_id'>[EDIT]</a>
<a href='movie.php?action=delete & id=$mov_id'>[DELETE]</a>
<td>
</tr>
eod;
while($row=mysql_fetch_array($result))
{
$mov_id=$row["id"];
$mov_name=$row["name"];
echo $ta_row;
}
?>
now the above code didnt print the name or the id of the movie(the fields were blank)...so i cut and paste $ta_row inside the while loop after the definition of $mov_id and $mov_name...this sorted out all problems...but my question is why did the code fail earlier...as it is i was outputting ta_row after defining $mov_id and $mov_name so if $ta_row is just a string its content variables should have got changed...why didnt they change?
Because a heredoc is just like any other string - it's value is fixed when you declare it. If the variables $mov_id and $mov_name weren't set when you declared $ta_row, you can't use them in $ta_row.
If you want to do something like you tried to do in the first place, you would have to use something like str_replace() or sprintf() - replace place-holders in the original string with the actual values you want to display.
Consider this:
$myVar = "Some string containing a $var";
$var = 'Variable';
echo $myVar;
// Outputs: Some string containing a
Now this:
$var = 'Variable';
$myVar = "Some string containing a $var";
echo $myVar;
// Outputs: Some string containing a Variable
...Heredocs behave exactly like a double-quoted string (from this point of view, at least).
Alternatively you could do this:
$myVar = 'Some string containing a $var';
$var = 'Variable';
echo $myVar;
// Outputs: Some string containing a $var
echo str_replace('$var',$var,$myVar);
// Outputs: Some string containing a Variable
...because $myVar is now single-quoted, $var appears in it literally. Then when you run str_replace(), it is replaced with the value of $var, instead of the literal string.
It's probably worth you re-reading this.
It didn't work when you had it before the loop because it was trying to use the value of the variables $mov_id and $mov_name as they existed right then. Since they weren't defined at that point in the code, there was nothing to add in there. After that, $ta_row was simply a variable that contained a string, and only a string -- no variables, of the HTML.
If you'd like to move it out of the loop, use some placeholders like ##MOV_ID## and ##MOV_NAME## then you can just
echo str_replace(array('##MOV_ID##', '##MOV_NAME##', array($mov_id, $mov_name), $ta_row);
to get the desired result
Related
I'm not even sure if what I am trying to do is possible, I have a simple php echo line as below..
<?php echo $T1R[0]['Site']; ?>
This works well but I want to make the "1" in the $T1R to be fluid, is it possible to do something like ..
<?php echo $T + '$row_ColNumC['ColNaumNo']' + R[0]['Site']; ?>
Where the 1 is replaced with the content of ColNaumNo i.e. the returned result might be..
<?php echo $T32R[0]['Site']; ?>
It is possible in PHP. The concept is called "variable variables".
The idea is simple: you generate the variable name you want to use and store it in another variable:
$name = 'T'.$row_ColNumC['ColNaumNo'].'R';
Pay attention to the string concatenation operator. PHP uses a dot (.) for this, not the plus sign (+).
If the value of $row_ColNumc['ColNaumNo'] is 32 then the value stored in variable $name is 'T32R';
You can then prepend the variable $name with an extra $ to use it as the name of another variable (indirection). The code echo($$name); prints the content of variable $T32R (if any).
If the variable $T32R stores an array then the syntax $$name[0] is ambiguous and the parser needs a hint to interpret it. It is well explained in the documentation page (of the variable variables):
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.
You can do like this
$T1R[0]['Site'] = "test";
$c = 1;
$a = "T".$c."R";
$b = $$a;
echo "<pre>";
print_r($b[0]['Site']);
Or more simpler like this
$T1R[0]['Site'] = "test";
$c = 1;
$a = "T".$c."R";
echo "<pre>";
print_r(${$a}[0]['Site']);
I have a simple PHP file with the following:
<?php
echo 'catid=$_GET["catid"]';
<?>
When I run the page, the output is:
catid=$_GET["catid"]
I'm accessing the page as www.abc.com/temp.php?catid=3. I'd like $_GET to execute so I see:
catid=3
What am I doing wrong?
You have to cancat the two:
echo 'catid=' . $_GET["catid"];
or you could use " (double quotes):
echo "catId=$someVar";
$_Get is a variable, and to echo a variable you do not need parenthesis around it.
<?php
echo 'catid='.$_GET["catid"];
?>
please see this : source
You can use non-array variables for that:
$getCatID = $_GET["catid"];
echo "catid=$getCatID";
Or you can use (recommended):
echo 'catid=' . $_GET["catid"];
You may try:
echo "catid= {$_GET['catid']}";
The best way to use variables in string is:
echo "catid={$_GET['catid']}";
You have to use double quoted string to notify PHP that it might contains variables inside. $_GET is array, so you will need to put the variable statement in {}.
<?php
echo "catid={$_GET['catid']}";
?>
There are a few options to combine a variable with a string.
<?php
$var = "something";
// prints some something
echo 'some ' . $var; // I prefer to go for this one
// prints some something
echo "some $var";
// prints some $var
echo 'some $var';
// prints some something
echo "some {$var}";
?>
I can make out the difference between
echo "{$var1}someString" // here the variable is $var1
echo "$var1someString" // here the variable is $var1someString
The question is why to use {}? It works only with {}. It does not work with (). What is so special about { }?
The curly braces {} are used in that way to identify variables within strings:
echo "{$var1}someString"
If you look at:
echo "$var1someString"
PHP can't possibly determine that you wanted to echo $var1, it's going to take all of it as the variable name.
You could concatenate your variables instead:
echo $var1 . "someString"
It doesn't work for () simply because the PHP designers choose {}.
you expained it yourself. thats simply the syntax php uses for this - nothing more. to quote the documentation:
Complex (curly) syntax
Simply write the expression the same way as it would appear outside the string, and then wrap it in { and }. Since { can not be escaped, this syntax will only be recognised when the $ immediately follows the {. Use {\$ to get a literal {$
According to the documentation of string, the curly part is called complex syntax. It basically allows you to use complex expressions inside string.
Example from the documentation:
<?php
// Show all errors
error_reporting(E_ALL);
$great = 'fantastic';
// Won't work, outputs: This is { fantastic}
echo "This is { $great}";
// Works, outputs: This is fantastic
echo "This is {$great}";
echo "This is ${great}";
// Works
echo "This square is {$square->width}00 centimeters broad.";
// Works, quoted keys only work using the curly brace syntax
echo "This works: {$arr['key']}";
// Works
echo "This works: {$arr[4][3]}";
// This is wrong for the same reason as $foo[bar] is wrong outside a string.
// In other words, it will still work, but only because PHP first looks for a
// constant named foo; an error of level E_NOTICE (undefined constant) will be
// thrown.
echo "This is wrong: {$arr[foo][3]}";
// Works. When using multi-dimensional arrays, always use braces around arrays
// when inside of strings
echo "This works: {$arr['foo'][3]}";
// Works.
echo "This works: " . $arr['foo'][3];
echo "This works too: {$obj->values[3]->name}";
echo "This is the value of the var named $name: {${$name}}";
echo "This is the value of the var named by the return value of getName(): {${getName()}}";
echo "This is the value of the var named by the return value of \$object->getName(): {${$object->getName()}}";
// Won't work, outputs: This is the return value of getName(): {getName()}
echo "This is the return value of getName(): {getName()}";
?>
Here {} define that variable within these are not a simple string so php pic up that variable value instead of assuming that as a simple string.
I need to make a dynamic variable based on a loop, what i am looking for is a variable something like
$var = "foo";
$$var = "bar";
echo $foo; // bar
but for me it should be more like a fixed parameter attached to the dynamic part like
$var='123';
$'current_'.$$var=some value; // not correct syntax
echo $current_123 should give 'some value';
Use curly braces:
$${'current_' . $var} = $some_value;
What is the meaning of { } (curly braces) in string literals in PHP?
This is the complex (curly) syntax for string interpolation. From the manual:
Complex (curly) syntax
This isn't called complex because the syntax is complex, but because
it allows for the use of complex expressions.
Any scalar variable, array element or object property with a string
representation can be included via this syntax. Simply write the
expression the same way as it would appear outside the string, and
then wrap it in { and }. Since { can not be escaped, this syntax
will only be recognised when the $ immediately follows the {. Use
{\$ to get a literal {$. Some examples to make it clear:
<?php
// Show all errors
error_reporting(E_ALL);
$great = 'fantastic';
// Won't work, outputs: This is { fantastic}
echo "This is { $great}";
// Works, outputs: This is fantastic
echo "This is {$great}";
echo "This is ${great}";
// Works
echo "This square is {$square->width}00 centimeters broad.";
// Works, quoted keys only work using the curly brace syntax
echo "This works: {$arr['key']}";
// Works
echo "This works: {$arr[4][3]}";
// This is wrong for the same reason as $foo[bar] is wrong outside a string.
// In other words, it will still work, but only because PHP first looks for a
// constant named foo; an error of level E_NOTICE (undefined constant) will be
// thrown.
echo "This is wrong: {$arr[foo][3]}";
// Works. When using multi-dimensional arrays, always use braces around arrays
// when inside of strings
echo "This works: {$arr['foo'][3]}";
// Works.
echo "This works: " . $arr['foo'][3];
echo "This works too: {$obj->values[3]->name}";
echo "This is the value of the var named $name: {${$name}}";
echo "This is the value of the var named by the return value of getName(): {${getName()}}";
echo "This is the value of the var named by the return value of \$object->getName(): {${$object->getName()}}";
// Won't work, outputs: This is the return value of getName(): {getName()}
echo "This is the return value of getName(): {getName()}";
?>
Often, this syntax is unnecessary. For example, this:
$a = 'abcd';
$out = "$a $a"; // "abcd abcd";
behaves exactly the same as this:
$out = "{$a} {$a}"; // same
So the curly braces are unnecessary. But this:
$out = "$aefgh";
will, depending on your error level, either not work or produce an error because there's no variable named $aefgh, so you need to do:
$out = "${a}efgh"; // or
$out = "{$a}efgh";
As for me, curly braces serve as a substitution for concatenation, they are quicker to type and code looks cleaner. Remember to use double quotes (" ") as their content is parsed by PHP, because in single quotes (' ') you'll get the literal name of variable provided:
<?php
$a = '12345';
// This works:
echo "qwe{$a}rty"; // qwe12345rty, using braces
echo "qwe" . $a . "rty"; // qwe12345rty, concatenation used
// Does not work:
echo 'qwe{$a}rty'; // qwe{$a}rty, single quotes are not parsed
echo "qwe$arty"; // qwe, because $a became $arty, which is undefined
?>
Example:
$number = 4;
print "You have the {$number}th edition book";
//output: "You have the 4th edition book";
Without curly braces PHP would try to find a variable named $numberth, that doesn't exist!
I've also found it useful to access object attributes where the attribute names vary by some iterator. For example, I have used the pattern below for a set of time periods: hour, day, month.
$periods=array('hour', 'day', 'month');
foreach ($periods as $period)
{
$this->{'value_'.$period}=1;
}
This same pattern can also be used to access class methods. Just build up the method name in the same manner, using strings and string variables.
You could easily argue to just use an array for the value storage by period. If this application were PHP only, I would agree. I use this pattern when the class attributes map to fields in a database table. While it is possible to store arrays in a database using serialization, it is inefficient, and pointless if the individual fields must be indexed. I often add an array of the field names, keyed by the iterator, for the best of both worlds.
class timevalues
{
// Database table values:
public $value_hour; // maps to values.value_hour
public $value_day; // maps to values.value_day
public $value_month; // maps to values.value_month
public $values=array();
public function __construct()
{
$this->value_hour=0;
$this->value_day=0;
$this->value_month=0;
$this->values=array(
'hour'=>$this->value_hour,
'day'=>$this->value_day,
'month'=>$this->value_month,
);
}
}