PHP: single and double quotes issue in echo-ed string? - php

I have a very simple issue which I don't know how to fix.
Basically, I have this string:
$variable = '<input type="button" value="something" onclick="location.href = 'my-page.php';" />';
the issue is the onclick="..." on the button.
when i run my code, it kills the entire page without any errors.
Could someone please let me know if there is a way to sort this out?

You need to escape the apostrophes:
$variable = '<input ... onclick="location.href = \'my-page.php\';" />';

Related

php use hidden post to pass dynamic data to another php file

I'm trying to build a comment system, each comment has a unique id, many comments can be associated with a post, and each post has a unique id. I want to pass the post id to a submit.php file (where comments are update to the database), but no matter what I tried I just can't pass the data. Currently I have something like this:
$sql="SELECT postid,post,pdate FROM posts";
$result = mysql_query($sql);
while($row = mysql_fetch_array($result)) {
echo '$row["post"]';
echo '<form action="submit.php" method="POST">';
echo '<input name="comment" type="text" id="comments"></input>';
echo '<input type="hidden" name="id" value="$row["postid"]" />';
echo '<input type="submit" value="enter comments" />';
}
?>
for testing purpose I have submit.php as follows,
<?php
$ha=$_POST['id'];
echo $ha;
?>
data of postid is not passed, and I just got "$row[" as output.
inside the while loop if I say $haha=$row["postid"]; echo "$haha"; then each individual post id will be printed correctly, but I just cannot pass the data to submit.php file.
update: I just changed my code to :
echo '<input type="hidden" name="id" value="' . $row["postid"] . '" />';
Now a number is succesfully passed to submit.php, the problem is ,it's always "3". My post id ranges from 3 to 13, post with id=3 is at the bottom of the page and post with id=13 is at the top.However,if I write a comment at the post with id=13(same issue occur to other posts as well), after clicking submit, the data passed to submit.php is always 3. Is there something wrong with the while loop?
Another update: it's always 3 because i forget to close the form tag, now everything worked perfectly
you're using single quote, so you cannot insert variables inside of string, use
echo '<input type="hidden" name="id" value="' . $row["postid"] . '" />';
In PHP, you can wrap a string in single-quotes ('), or double quotes (").
When you use single quotes, the string is not interpreted - this means that all the characters are left intact, and no variables are parsed.
When you use double quotes, any variables in the string will be replaced with their value.
In your case, you're using single quotes, so your variable is not being interpreted and converted. Instead, use double quotes:
$sql="SELECT postid,post,pdate FROM posts";
$result = mysql_query($sql);
while ($row = mysql_fetch_array($result)) {
echo $row["post"];
echo '<form action="submit.php" method="POST">';
echo '<input name="comment" type="text" id="comments"></input>';
echo "<input type=\"hidden\" name=\"id\" value=\"{$row["postid"]}\" />";
//Alternatively, keep the single quotes and use the concatenation method:
//echo '<input type="hidden" name="id" value="' . $row["postid"] . '" />';
echo '<input type="submit" value="enter comments" />';
//Also, if you're opening a form tag in this loop, be sure to close it
echo '</form>';
}
Some other things to note:
When you use double quotes to wrap your string, and you have double quotes inside your string, you must escape them (using a \). Notice name="id" became name=\"id\"; and
When referencing an item in an array within a string, you can either use string concatenation to ensure the full variable is interpreted correctly (value=\"" . $row["postid"] . "\"), or you can leave the variable in place and wrap it in curly brackets - which is my preference and is what is used above. If you're going to use the concatenation method, then you can keep the single quotes wrapping everything else - there are no variables to parse.
When echoing a variable value, you don't need to wrap it in anything - notice I removed the quotes from the first echo.
Here is PHP's documentation on strings, including single and double quoted strings: http://php.net/manual/en/language.types.string.php.
And here is PHP's documentation on string operators: http://php.net/manual/en/language.operators.string.php.
Try adding a conditional at the start of your file like this just to be sure the form is actually submitted properly:
<?php
if(isset($_POST['submit_form'])) {
$ha=$_POST['id'];
echo $ha;
}
with your button like this
<input type="submit" value="enter comments" name="submit_form"/>
and please close your form tag.
You can pass value as follow,
echo '<input type="hidden" name="id" value="' . $row["postid"] . '" >';

How to escape MS-SQL output in html/php?

Sounds very simple, but I'm kinda confused at the moment.
I have this DB object which includes some values that I want to output in an html form.
Simplified Problem:
$result is my db object and this is the html input where I want to output some text which can include double or single quotes.
<input class="someclass" name="desc" id="descID" type="text" value="<?=$result['desc'];?>" placeholder="<Description>" />
So if $result['desc'] contains text like this: 'Did you hear about "foobar"?'
everything after the first double quote gets cut off and ends up like this: 'Did you hear about '.
What i have tried already without success:
htmlspecialchars like this value="<?=htmlspecialchars($result['desc']);?>" or like this value="<?=htmlspecialchars($result['desc'], ENT_QUOTES);?>"
addslashes
Note: My DB(mssql) saves the string properly. Only have the problems in my html.
I would be glad if you could help me out here. Thanks.
Thanks for the help so far, but i managed to find a solution to this:
<?$descEscaped = str_replace('"', '"', $result['desc']);?>
<input class="someclass" name="desc" id="descID" type="text" value="<?= htmlspecialchars($descEscaped);?>" />
htmlspecialchars replaces quotes with """.
I am using my simple function htmlliteral:
function htmlliteral($s){
return '"'.htmlspecialchars($s).'"';
}
With this function you can use:
$descEscaped = htmlliteral($result['desc']);
print "<input class=someclass name=desc id=descID type=text value=$descEscaped />";

PHP escaping syntax again

Thanks again for the help with a similar question earlier. I have one more similar, but I think more complicated.
It looks like this in HTML:
<input type="button" class="formButtonDeleteButton" value="" onclick="document.getElementById('WADADeleteRecordID').value=<?php echo($row_WADAactivities2['ActivityID']); ?>;document.getElementById('WADADeleteRecordName').innerHTML='<?php echo($row_WADAactivities2['Activity']); ?>';document.getElementById('deleteBox').style.display = 'block';document.getElementById('deleteMessage').style.display = 'table';" />
I get so far with it, but just get a bit lost, e.g.:
echo '<input type="button" class="formButtonDeleteButton" value="" onclick="document.getElementById('WADADeleteRecordID').value=' . rawurlencode($row_WADAactivities2['ActivityID']) . ;document.getElementById('WADADeleteRecordName').innerHTML=' . rawurlencode($row_WADAactivities2['Activity']);';document.getElementById('deleteBox').style.display = 'block';document.getElementById('deleteMessage').style.display = 'table';" \"/>";
This is pretty much the last bit of something I've been looking at that needs tidying up.
Thanks again.
You need to escape all the single-quote characters that are inside the single-quoted string:
echo '<input type="button" class="formButtonDeleteButton" value="" onclick="document.getElementById(\'WADADeleteRecordID\').value=' . rawurlencode($row_WADAactivities2['ActivityID']) . ;document.getElementById(\'WADADeleteRecordName\').innerHTML=' . rawurlencode($row_WADAactivities2['Activity']);';document.getElementById(\'deleteBox\').style.display = \'block\';document.getElementById(\'deleteMessage\').style.display = \'tabl\e';" \"/>";
I strongly recommend against writing such long strings of inline Javascript. Move it out into a Javascript function, and use onclick="functionName(...)".
See, you should always decide on whether or not its necessary to even echo something like this, or instead just use short tags like <?=$someVar?> directly in your view section of the code. Why? Because its much easier to deal with NOT escaping quotes :D Anyway, the way you should choose your quotes single or double, is if you're planning on NOT having any variables inside the string, use single quotes..if you're planning on using variables in the string use double quotes to avoid having to concatenate. Since you've used single quotes, you don't have to escape doubles, but you do have to escape other single quotes inside:
echo '<input type="button" class="formButtonDeleteButton" value="" onclick="document.getElementById(\'WADADeleteRecordID\').value=' . rawurlencode($row_WADAactivities2['ActivityID']) .' ;document.getElementById(\'WADADeleteRecordName\').innerHTML=' . rawurlencode($row_WADAactivities2['Activity']).';document.getElementById(\'deleteBox\').style.display = \'block\';document.getElementById(\'deleteMessage\').style.display = \'table\';" />';

Parameters in Javascript using jquery

I'm trying to pass a parameter from php into my javascript function inside html. Is this at all possible? This is what I've got so far, but it seems to crash once it hits the condition:
$str="<input type='submit' value='-' onclick='Call(".$row['field1'].");'/>";
I hope that I won't have to find a work around for this.
Thanks.
EDIT:
This is the function that I'm trying to call
function Call(stuff)
{
alert(stuff);
$.get('reports.php',
{'param':'section', 'text':stuff},
function(returned_data)
{
alert(returned_data);
});
//alert('end');
}
And this is the function that I'm populating a table with.
function PopTable()
{
alert('end');
document.getElementById('table').innerHTML = 'Loading...';
$.get('reports.php',
{'param':'getstuff'},
function(returned_data)
{
document.getElementById('table').innerHTML = returned_data; // Clear the select
});
alert('end');
}
This is the php that I'm sending back population the table:
$str.= '<tr>';
$str.='<td bgcolor="#ffffff">' . $row['stuff'] .'</td>';
$str.='<td><input type='submit' value='-' onclick="Call('$row['stuff']');"/></td>';
$str.='</tr>'; //accumulate table
I can't seem to get a return value for Call(), and the alert doesn't even pop up
Try:
$str='<input type="submit" value="-" onclick="Call(\''.$row['field1'].'\');"/>';
I would bet you need quotes around the value if it is a string value
For example if $row['field1'] = 'test'; then:
Your version: <input type='submit' value='-' onclick='Call(test);'/> which would fail because test is not a valid variable
My Version <input type="submit" value="-" onclick="Call('test');"/> which would work becase 'test' is a string
What you're trying to do is possible, whereas it is not possible to pass a parameter from JavaScript into a PHP function.
When you say it crashes once it hits the condition, do you mean when you click on the input on the page? In that case, it's an error in your JavaScript syntax. I would try using Firebug with Firefox to track down the issue.
My first guess is there are no quotation marks inside the Call() method. So you're doing this:
Call(something)
and it should be like this:
Call('something')
This is possible, but I would be very careful about mixing PHP echos and javascript inline with strings because you need to escape javascript datatypes properly
In your example, $row['field1'] is probably from a database, so it's a string, so you need to surround the value with quotes in your javascript call. But that's not all, because what if there's a quote in your string, or a special character like a newline which needs to be escaped in javascript? And then what about html escaping?
A better approach is to import your javascript values in one place using json_encode(), then use your variables from there.
E.g.:
<?php
$jsonrow = json_encode($row);
?>
<script type="text/javascript">
var jsrow = <?=htmlspecialchars($jsonrow);?>;
</script>
<?php // some time later... ?>
<input type="submit" value="-" onclick="Call(jsrow.field1);" />

Insert value into a text box which is inside an echo statement

I have this code basis:
echo '<input required type = "text" name = "subject1" value="XXX" />';
However, I would like XXX to be a variable, I have searched this online, but all the things that one of the discussions says is to do this:
value=\"$firstName\"
or
value='$firstName'
I have tried both of these, but they don't work, and I was hoping that someone could help me with this problem, basically, what I want is to be able to asign the value of a text edit to a variable in php, but when the text edit itself, is embedded in an echo, nothing seems to work.
Thanks
Concatenation is a pretty easy way to go about this:
echo '<input required type = "text" name = "subject1" value="' . $foo . '" />'
edit: Those spaces around the concatenation .'s (. $foo .) aren't required - I just add them fore readability.
I think the problem is you are using single quotes, so variables are not rendered automatically... you can concat with . like this:
echo 'some text' . $variable . 'some more text';
echo '<input required type="text" name = "subject1 value="<?php echo $value; ?>" />';
acutally you don't need the php echo .... stuff.... /* brain not engaged */

Categories