I'm having trouble escaping the PHP variable inside the getItems function:
while($row = mysql_fetch_array( $data ))
{
echo "<div class='favorite'>";
echo "<div style='display: inline;'>".$row['Item']."</div>";
if ($row['UID'] = $uid) {
echo "<div id='unlock'>Info</div>";
} else {
echo "<div id='unlock' onclick='getItems('".$row['Item']."')'>Unlock</div>";
}
echo "</div>";
}
When rendered (is render the word?) anyway, when I see it on my site it says:
onclick="getItems(" whatever')'
What am I doing wrong?
You can see the code here:
http://www.chusmix.com/game/insert/get-items.php?user=19
Your problem is that your attribute values are surrounded by single quotes, but you're also using single quotes in your javascript.
You'll have to use double quotes in your javascript. However, since the whole string (in PHP) is surrounded by double quotes, you'll have to escape them. Hence:
echo "<div id='unlock' onclick='getItems(\"".$row['Item']."\")' style='display: inline; float: right;'>Unlock</div>";
Or like this:
echo "<div id='unlock' onclick='getItems(\"{$row['Item']}\")' style='display: inline; float: right;'>Unlock</div>";
To clarify what the curly braces do (from the PHP docs):
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 }.
To further explain, let's say we have the following scenario:
$name = 'Apple';
$sentence = "$names are my favorite fruit";
What I'm trying to get is: Apples are my favorite fruit. However, this won't work. PHP will instead be looking for a variable called $names, and when it doesn't find it, it'll complain.
So, to remedy this, we can surround our variable in curly braces:
$name = 'Apple';
$sentence = "{$name}s are my favorite fruit";
Great! Now PHP will know where the variable name ends and the string starts.
On a side note: You might consider switching to double-quoting your attributes, since the way you do it now is not valid xHTML (unless you don't care).
Yes, there is a problem with your quotes. It should be this:
echo "<div id='unlock' onclick='getItems(\"".$row['Item']."\");' style='display: inline; float: right;'>Unlock</div>";
The problem is that your opening quotes for onclick and the quotes around the function arguement have to be a different kind of quote.
This is much easier though to do with html and then just insert the variable like this:
<div id="unlock" onclick="getItems('<?=$row['Item'];?>');" style="display: inline; float: right;">Unlock</div>
Doing things this way instead of echoing HTML when possible will save you tons of time and confusion, and you won't have to worry about all the escaping of quotes
The ' inside onclick is closing the onclick itself. Change it to:
onclick='getItems(\"".$row['Item']."\")'
That way, in JS, it uses a different type of quote.
Even better... you can leave PHP, and have one less type of quote to worry about.
else { ?>
<div id='unlock' onclick='getItems("<?=$row['Item'];?>")' style='display: inline; float: right;'>Unlock</div>
<?php
}
or like so:
echo '<div id="unlock" onclick="getItems('."'".$row['Item']."'".')" style="display: inline; float: right;">Unlock</div>';
If I had to do this, it would have looked like:
<?php while(true) :?>
<div class="favorite">
<div style="display: inline;"><?php echo $row['Item'];?></div>
<?php if ($row['UID'] = $uid):?>
<div id="unlock">Info</div>
<?php else: ?>
<div id="unlock" onclick="getItems('<?php echo $row['Item']; ?>)">Unlock</div>
<?php endif;?>
</div>
<?php endwhile;?>
try the following .
edit: changed to make sure quotes were escaped correctly
echo "<div id='unlock' onclick=\"getItems('{$nameArray[0]}')\" ></div>";
Related
Very unusual question.
I came across some code some years in the pass that was including conditions and normal PHP syntax while echoing all content.
My question is how is that Technic/syntax called. I have been googling with some very broad terms and can't find what im looking for.
If my memory is correct, The code I viewed long time ago had un-escaped HTML and it was not required to start and stop PHP processing with <?php ?>
I Have a method within a class called Template\Labels::User()
the only purpose of that method is to echo the proper html to create a label within my webapp so that the pages are lighten of code and clear to anyone viewing the code.
Id like to avoid, having to <?php ?> for very simple boolean if
Any one know what I am looking for ?
static function User($UserObj,$isLink = true){
?>
<div class="image label bg-purple" style="margin: 4px;">
<?php if($isLink){
?><a href=""><?php
} ?>
<img src="<?php echo $UserObj -> ProfilePicture; ?>" style="height: 2em;" class="img-circle" alt="User Image">
<label style="font-size: 90%"><?php echo $UserObj->FirstName{0}.$UserObj->LastName{0}; ?></label>
<?php if($isLink){
?></a><?php
} ?>
</div>
<?php
}
Edited
After some more research by going through PHP documentation on Operator
I found Nowdoc string quoting
Can someone shed some light onto Nowdocs are to single-quoted strings what heredocs are to double-quoted strings. A nowdoc is specified similarly to a heredoc, but no parsing is done inside a nowdoc. The construct is ideal for embedding PHP code or other large blocks of text without the need for escaping. It shares some features in common with the SGML
http://php.net/manual/en/language.types.string.php#language.types.string.syntax.nowdoc
Its good that you added code to your question so that we can all see what you are dealing with here. Now to me what I understand with your question is that you want to avoid using php tags to echo some html code based on if condition.
<?php
static function User($UserObj,$isLink = true){
$html = '<div class="image label bg-purple" style="margin: 4px;">';
if($isLink) $html .= '<a href="">';
$html .= '<img src="'.#$UserObj->ProfilePicture.'" style="height: 2em;" class="img-circle" alt="User Image">';
$html .= '<label style="font-size: 90%">'.#$UserObj->FirstName[0].#$UserObj->LastName[0].'</label>';
if($isLink) $html .= '</a>';
echo $html;
}
?>
In my thinking I thought you should just have to run php tags once and use a simple variable to add your html code to so that you can print at the end of the function.
I didn't understand some of your images but all the same your issue is printing unescaped html in PHP. In other words you want to have raw html.
There are two functions am thinking of right now which you can use depending on your desired output: html_entity_decode() and htmlentities().
html_entity_decode() is the opposite of htmlentities() in that it converts all HTML entities in the string to their applicable characters.
<?php $orig = "I'll \"walk\" the <b>d
$a = htmlentities($orig);
$b = html_entity_decode($a);
echo $a; // I'll "walk"
echo $b; // I'll "walk" the <b>
?>
Ref: http://www.php.net/html_entity_decode
I hope this helps solve your issue of unescaped html.
Im new to learning PHP as you might have guessed. I have the contents of a .txt file echoed but I would like it to stand out more, so I figured I would make it a different colour.
My code without colour:
<?php
$file = fopen("instructions.txt", "r") or exit("Unable to open file");
while(!feof($file))
{
echo fgets($file);
}
fclose($file);
?>
I have researched this and seen suggestions to others to use a div style, however this didn't work for me, it gave me red errors all the way down the page instead! I think its because I'm using 'fgets' not just a variable? Is there a way to colour the echo red?
The code I tried but doesn't work:
echo "<div style=\"color: red;\">fgets($file)</div>";
(In general) You need to separate the actual PHP code from the literal portions of your strings. One way is to use the string concatenation operator .. E.g.
echo "<div style=\"color: red;\">" . fgets($file) . "</div>";
String Operators
Other answer already told that you can't use a function call in a double quoted string. Let additionally mention that for formatting only tasks a <span> element is better suited than a <div> element.
Like this: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/span
You should try:
<div style="color: red;"><?= fgets($file);?></div>
Note: <?= is an short hand method for <?php echo fgets($file);?>
This version does not need to escape double quotes:
echo '<div style="color:red;">' . fgets($file) . '</div>';
You can do this with the concatenate operator . as has already been mentioned but IMO it's cleaner to use sprintf like this:
echo sprintf("<div style='color: red;'>%s</div>", fgets($file));
This method comes into it's own if you have two sets of text that you want to insert a string in different places eg:
echo sprintf("<div style='color: red;'>%s</div><div style='color: blue;'>%s</div>", fgets($file), fgets($file2));
I'm trying to pull $username from my database as a greeting. How would I output a variable within my else statement?
The variable username is equal to the following:
$username = htmlentities($_SESSION['user']['username'], ENT_QUOTES, 'UTF-8');
<?php
if($_GET["p"] == 'login') {
echo "";
} else {
echo "<div class='row'><div class='logo'><img style='margin-left: -21px;' src='http://localhost/ncms/images/logo.png' /></div><p class='panel radius topinfo'>Welcome . $username .</p>";
}?>
You could use string formatting.
printf("<div class='row'><div class='logo'><img style='margin-left: -21px;' src='http://localhost/ncms/images/logo.png' /></div><p class='panel radius topinfo'>Welcome %s</p>", $username);
Alright. Fixed it. Sorry for the confusion to you guys on this one, I had to put the variable inside of my function set that starts the session. Doh!
Sorry again guys and thank you for the tips though I forgot how to concatenate for a second there lol.
Php variables auto-expand when used in double quotes, but these are usually used for specifying attribute vales in HTML.
I find the easiest way to remember the rules when echoing HTML is to use single quotes for the HTML, double quotes for the attribute values and string concatonation for php variables.
echo '<div class="row"><div class="logo"><img style="margin-left: -21px;" src="http://localhost/ncms/images/logo.png" /></div></div><p class="panel radius topinfo">Welcome '. $username .'</p>';
You're also missing a closing div (added above).
when using the double quote you don't need to concatenate the text string. you can change it to
echo "<div class='row'><div class='logo'><img style='margin-left: -21px;' src='http://localhost/ncms/images/logo.png' /></div><p class='panel radius topinfo'>Welcome $username</p>";
I did not attempt to fix the errors in the code other than the question asked. Validators should be used as suggested in other answers.
It's probably stupid question, but I can not find an answer. How can I style echo output with css? I have this code:
echo "<div id="errormsg"> Error </div>";
Now it displays syntax error, I think because of those quotes around errormsg. I've tried single quotes, but with no effect. Thank you
When outputting HTML, it's easier to use single quotes so you can use proper double quotes inside like so:
echo '<div id="errormsg"> Error </div>';
That will get rid of your parse error... To edit the style you will need to use CSS with the selector of #errormsg like so:
#errormsg {
color: red;
}
try
echo "<div id=\"errormsg\"> Error </div>";
First you need to either use single-quotes to surround the attribute value:
echo "<div id='errormsg'> Error </div>";
Or you could reverse that, to give:
echo '<div id="errormsg"> Error </div>';
Or you should escape the quotes:
echo "<div id=\"errormsg\"> Error </div>";
And then style the resulting element with the CSS:
#errormsg {
/* css */
}
The syntax problem you were encountering is a result of terminating the string and then having a disparate element between the first and second strings, with which PHP has no idea what to do.
To put double quotes inside of a double-quoted string, you need to "escape" them by putting blackslashes before them:
echo "<div id=\"errormsg\"> Error </div>";
In this case, another choice is to use single quotes for one or the other.
echo "<div id='errormsg'> Error </div>";
echo '<div id="errormsg"> Error </div>';
PHP's documentation has a section explaining the different string syntaxes, which should explain everything you could want to know about this subject.
Use single quotes around errormsg and what you have should work just fine. Alternatively, but less tidy, you can escape the double quotes with a backslash.
echo "<div id='errormsg'> Error </div>";
You are getting a syntax error because you are including unescaped double quotes inside a string that is delimited by double quotes.
Either escape them
echo "<div id=\"errormsg\"> Error </div>";
or use single quotes
echo '<div id="errormsg"> Error </div>';
The browser doesn't care if you generated markup using echo or something else. It just sees the HTML you send to it.
For the above markup, you can style it using an id selector:
#errormsg { /* … */ }
The usual rules for the cascade (including specificity) will apply.
If you don't want to care about single quotes or double quotes then the better way to achieve your answer is to use heredoc syntax .
Your solution :
<?php
$heredoc = <<< EOT
<div id="errormsg">Error solved</div>
EOT;
echo "$heredoc";
?>
css :
#errormsg{color: green;}
WARNING :
Do not add whiteSpace after <<< EOT
Do not add whiteSpace before EOT;
Do not add whiteSpace between EOT and ;
Do not add whiteSpace after EOT;
EOT; must be in new line.
<?php
$total=3;
echo '
<div class="idsdiv">.$total.<div> ';
?>
i want to appear $total variable number in the link.why is this script not working?
Enclose the whole string with double quotes to embed variables inside:
echo "<div class=\"idsdiv\">$total<div>";
You need to use double quotes around your HTML and single quotes around your attributes or do this...
echo '<div class="idsdiv">' . $total . '<div> ';
PHP doesn't process variable names in strings enclosed in single quotes.
<?php
$total=3;
echo '<div class="idsdiv">',$total,'<div>';
?>
Look at the string section of php.net (http://php.net/string) they talk about how to use each of the types. One of quote being the ' where nothing is parsed.
<?php $total=3;
echo "<div class=\"idsdiv\">$total<div> ";
?>
you had errors with your quotes
You can print HTML without printing it, like so:
<?php
$total = 3;
?>
<div class="idsdiv"><?php echo $total; ?></div>
When I still did PHP, I found it much easier to manage than escaping tons of quotes and things like that.
You can even do it inside of an if block too:
<?php
if ($foo == 'bar') {
?>
<div>Foo is bar</div>
<?php
}
?>
The method I like is
<?php
$total=3;
echo "<div class='idsdiv'><a href='profile.php?id={$total}'>{$total}</a><div>";
?>
It is my method, but there are plenty of ways to do it. Maybe even too many. If you want more information you can always refer to the documentation.
<?php
$total=3;
echo '<div class="idsdiv">'.$total.'<div>';
?>
You're quote are missing before and after the $total