I have been using this code for deleting data from database. What i wan is whenever a user clicks an image link to delete data from the confirm function prompts up and ask for action, i am getting error in this code.
$delurl = "delete_dish.php?dish_id=".$row['id'];
$img = "<img src = 'images/delete.png'>";
echo "<a href=".$delurl.";
echo "onclick='return confirm('Are you sure you want to delete.')'>".$img."</a>";
Maybe the error is in double quotes or single quotes, Any help
Thanks in advance
change
echo "<a href=".$delurl.";
to
echo "<a href=\"".$delurl."\" ";
$delurl = "delete_dish.php?dish_id=".$row['id'];
$img = "<img src = 'images/delete.png'>";
$confirm_box <<<CONFIRM
<a href="$delurl"
onclick="return confirm('Are you sure you want to delete?')">$img</a>
CONFIRM;
// then elsewhere ...
echo $confirm_box
Always tend towards using the HEREDOC syntax to construct HTML/JS output, it will save you a lot of heartache. Just watch out for the major gotcha, DO NOT INDENT THE FIRST/LAST lines of the heredoc declaration.
EDIT The benefit being that you can mix single and double quotes as much as you like, you only have to worry about the JS quoting - PHP variables are interpolated without the quotes. You can further wrap curly quotes around your PHP variables like {$this} to make it easier to read, but also to delineate $this and {$this}tle.
I would us the following instead of escaping, this is more readable to me:
$delurl = "delete_dish.php?dish_id=".$row['id'];
$img = "<img src = 'images/delete.png'>";
?>
<?=$img?>
You can, may and should escape when handling stuff like this:
echo "<a href=\".$delurl.\"";
echo " onclick=\"return confirm('Are you sure you want to delete.')\">".$img."</a>";
lg,
flo
Related
Hello dear programmers,
I have a problem with the echoing of a html phrase with an onclick function that executes a javascript function. I want to build a tabpage, for a image gallery.
The echo:
echo "<div class='albumitem'><a class='tablinks' onclick='openAlbum(event, '".$album."')'><h1 class='galleryheader'>".$album."</h1></a><div id='".$album."' class='tabcontent'>";
Everything goes well, except the passing of the variable in the onclick function, as you can see here. What actually the HTML looks like:
<a class="tablinks" onclick="openAlbum(event, " aubing')'=""><h1 class="galleryheader">Aubing</h1></a>
But this onclick event has to look like this:
onclick="openAlbum(event, 'Aubing')"
Is there a way to actually realise this or do I have to find an other option?
I actually tried switching " with ', didnt go very well....
Thank you for everybody that tries to help
Try this:
echo "<div class='albumitem'><a class='tablinks' onclick='openAlbum(event, \"$album\")'><h1 class='galleryheader'>".$album."</h1></a><div id='".$album."' class='tabcontent'>";
see escaped double quotes in the onclick definition
addslashes is what you are looking exactly.And also you have to remove the single quotes in variable.Try to do the following way.
echo "<div class='albumitem'><a class='tablinks' onclick='openAlbum(event, '".addslashes($album)."')'><h1 class='galleryheader'>".$album."</h1></a><div id=".addslashes($album)." class='tabcontent'>";
Hope this help.
An alternative:
$escapedString = htmlspecialchars('This is a test string: < > & \' " end.', ENT_COMPAT);
echo "<div onclick='alert(this.dataset.name)' data-name=\"$escapedString\">Click Me</div>";
This approach avoid quotes inside function, no quotes nesting.
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 have a PHP script that generates some Javascript for me in a manner like this:
foreach ($array as $element)
{
echo '<a onClick="myFunctionTakesPHPValues('.$element[0].','.$element[1].')">'.$element[2].'</a>';
}
My problem is that how can I escape so that the Javascript bit will look more like
<a onClick='MyFunctionTakesPHPValues("'.$element[0].','.$element[1].'")>'.$element[2].'</a>';
I hope this makes sense. The short version is that I feel i need triple quotes inside double quotes inside single quotes, but there is no such thing as triple quotes, but I believe there is some way to escape quotes to nest it up three times.
Same as always: encode as JSON.
echo '<a onClick="myFunctionTakesPHPValues('.json_encode($element[0]).','.json_encode($element[1]).')">'.$element[2].'</a>';
Never echo JS from PHP. Escape from PHP mode instead, it will save you a lot of slashes and nerves.
Every value have to be escaped properly, as explained in this article
So, for the JS values you have to escape them with json_encode() and, as they are going into HTML attribute, escape them as HTML too.
For the last element only HTML encoding is required.
foreach ($array as $element)
{
$param1 = htmlspecialchars(json_encode($element[0])); // better give them
$param2 = htmlspecialchars(json_encode($element[1])); // meaningful names
$param3 = htmlspecialchars($element[2]);
?>
<a onClick="myFunctionTakesPHPValues(<?=$param1?>,<?=$param2?>)">
<?=$param3?>
</a>
<? }
And yes, using raw JS in HTML attributes considered as a bad practice.
Use Like
echo "<a onClick='myFunctionTakesPHPValues(\"".$element[0]."\",\"".$element[1]."\")'>".$element[2]."</a>";
Use this:
echo "<a onClick='MyFunctionTakesPHPValues(\"'".$element[0]."','".$element[1]."'\")>'".$element[2]."'</a>'";
foreach ($array as $element)
{?>
<a onClick="myFunctionTakesPHPValues("<?php echo $element[0].','.$element[1].')>'.$element[2].'</a>'
}
?>
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to get useful error messages in PHP?
Ive started on part of my new year resolution and decided to learn php, as part of it im trying to parse in an xml feed, and echo out the name of the events wrapped in <a> tags linking them back to the events page on the xml feed's site.
I think ive got it all in but i cant seem to see why this isnt working im just getting a blank page, if some one could point me in the right direction it would be much appreciated, cheers
<?php
// F1 W/H xml feed
$xml = simplexml_load_file('http://whdn.williamhill.com/pricefeed/openbet_cdn?action=template&template=getHierarchyByMarketType&classId=5&marketSort=HH&filterBIR=N');
foreach ($xml->response->williamhill->class->type as $type) {
$type_attrib = $type->attributes();
echo "<h2>".$type_attrib['name']."</h2>"; //Title - in this case f1 championship
} ?>
<ul>
<?php
foreach($type->market as $event) {
echo "<li>";
echo "<a href="$event_attributes['url']">";
echo $event_attributes['name'];
echo "</a>";
echo "</li>";
}
?>
</ul>
echo "<a href="$event_attributes['url']">";
try changing that line to
echo "<a href=\"".$event_attributes['url']."\">";
The Php parser is pretty funny about this. Usually you pick one and just stick to it, or use both single quotes and double quotes as you please. Just remember that strings with double quotes are parsed for variables.
$hello = "Hello";
echo "$hello master";
is the same as
$hello ="Hello";
echo $hello.' master';
When you are testing your PHP scripts, you'll find it useful to switch on errors - then PHP will actually tell you why it isn't showing you anything:
error_reporting(E_ALL);
Normally you will have missed a ; or mis-typed a variable name.
in your case the error is here:
echo "<a href="$event_attributes['url']">";
You have accidentally ended the string with a double quote, so PHP thinks the string ends here:
echo "<a href="
This is where using single-quotes can be very handy because your double quotes won't then close the string.
echo '<a href="' . $event_attributes['url'] . '">';
The main difference between single and double quotes in PHP is that double quotes has special clever parsing rules and single quotes doesn't. For example:
$myVar = "BLAH";
echo "Example $myVar"; // Example BLAH
echo 'Example $myVar'; // Example $myVar
In your unordered list, you should use a dot to concatenate your string, and escape your double quotes like this:
echo "<a href=\"".$event_attributes['url']."\">";
Instead of
echo "<a href="$event_attributes['url']">";
Your example throws and error because you haven't used proper string concatenation. However, even with correct concat, it would render as <a href=http://someurl>, and you'd need to add the double quotes according to html standard. Hence you have to double quote.
if you want to not be troubled by having to switch between using a ' or a " then i suggest using the php alternative syntax php alternative syntax
with the given code it would look like
<?php
// F1 W/H xml feed
$xml = simplexml_load_file('http://whdn.williamhill.com/pricefeed/openbet_cdn?action=template&template=getHierarchyByMarketType&classId=5&marketSort=HH&filterBIR=N');
foreach ($xml->response->williamhill->class->type as $type) {
$type_attrib = $type->attributes();
echo "<h2>".$type_attrib['name']."</h2>"; //Title - in this case f1 championship
} ?>
<ul>
<?php foreach($type->market as $event):?>
<li>
<a href="<?php echo $event_attributes['url']; ?>">
<?php echo $event_attributes['name']; ?>
</a>
</li>
<? endforeach;?>
</ul>
one advantage this would bring is that it would produce cleaner code since you can clearly distiguish your php code from your html which is the presentational part at the price writing all those other <?php ?> and as what others would claim a performance degradation. the choice is yours
Change
echo "<a href="$event_attributes['url']">";
for
echo "<a href=".$event_attributes['url'].">";
You are missing the periods in your second echo, where you have your $event_attributes['url']
<?php
foreach($type->market as $event) {
echo "<li>";
echo "<a href=".$event_attributes['url'].">";
echo $event_attributes['name'];
echo "</a>";
echo "</li>";
}
?>
I would recommend you to enable your error log, it would allow you to know the line with problems in any of your scripts.
How should I quote this:
<tr onclick="$.colorbox({href:'information1.html'});">
When put in an echo " "; ?
I have tried this:
echo "<tr onclick='$.colorbox({href:'information1.html'});'>";
Which shows a Jquery error.
And I tried this:
echo "<tr onclick="$.colorbox({href:'information1.html'});">";
Which shows a PHP error.
Any workarounds? Thanks
You need to escape the quotes symbols:
echo '<tr onclick="$.colorbox({href:\"information1.html\"});">'
Note that using inline script is not considered to be a good practice!
echo '<tr class="foo">'
In the javascript code:
$('.foo').click(function() {
$.colorbox({ href: "information1.html" });
});
Simply escape the quotes. Whilst on this subject I feel it important to mention the fact that generally speaking, you should use single quotes for 'code' and double quotes only for displayed strings.
This stems from C standards and keeping this consistent will help you in the future if for example you wanted to implement gettext() and translate your website into multiple languages.
echo '<tr onclick="$.colorbox({href:\'information1.html\'});\">';
Having said that, there's a better way to achieve what you're doing. Give the row an id:
<tr id="inforow" />
And use jQuery to bind to it's click event when the DOM is ready.
$(document).ready(function() {
$(".inforow").click(function() {
$.colorbox({href:'information1.html'});
});
});
Anytime you want to print a string with a quote in it, just use the escape character '\' to ignore the quote as a literal closing quote, like so:
echo "<tr onclick=\"$.colorbox({href:'information1.html'});\">";
echo "<tr onclick=\"$.colorbox({href:'information1.html'});\">";
echo "<tr onclick=\"$.colorbox({href:'information1.html'});\">";
Try that:
echo "<tr onclick=\"$.colorbox({href:'information1.html'});\">";
I would use PHP-methods instead of caring about the quotes
echo '<tr onclick="'.
htmlentities('$.colorbox('.json_encode(array('href'=>'information.html'))).')">';
...will always create proper JSON and proper HTML, no matter what characters you use.
NO NEED to quote it.
NO NEED to put in an echo " ";
Just leave it AS IS:
?>
<tr onclick="$.colorbox({href:'information1.html'});">
<?
as well as any other HTML.
It's PHP. It's embedded in HTML. You can leave PHP mode any time
Another way is using EOD
$string = <<<EOD
"duble quotation" and 'quotation' all enable
EOD;
echo $string;