PHP: Complicated String With Single and Double Quotes - php

I'm trying to pass GET variables inside the URL with a bit of html inside of my PHP but can't figure out the quotes situation. I need to embed two variables inside the URL. I have one in but don't know how to embed the other. Here is the string:
echo "<a href='?id=".($id-1)."' class='button'>PREVIOUS</a>";
and here is what I need to go inside
&City=$City
Thanks for the help

Its pretty simple,
echo "<a href='?id=".($id-1)."&city=" . $City . "' class='button'>PREVIOUS</a>";

In php double quotes "" can eval variables inside them.
$test = "123;"
echo "0$test456"; // prints 0123456
In your case you better use single quote ''.
echo '<a href=\'?id=' . ($id-1) . '&City=' . $City . '\' class=\'button\'>PREVIOUS</a>';
or better
echo 'PREVIOUS';

Use something like this:
echo "<a href='?id=".$id."&City=".$city."'>";

You do need (well, it's good practice anyway) to use & for your ampersand. Otherwise it's fairly straight forward;
echo "<a href='?id=".($id-1)."&City=$City' class='button'>PREVIOUS</a>";
This is because you are using double quotes, which means you can put variables directly into the string (there are some exceptions which you might need to put in curly brackets {}).
I suggest you get a text editor with syntax highlighting, such as jEdit (other editors are available).
Hope this helps.

Maybe is it better to use the sprintf function
$id = 100;
$previousId = $id - 1;
$City = 'Amsterdam';
$link = 'PREVIOUS';
echo sprintf($link, $id, $City);

Related

PHP - Echo out database information into a string

I am simply trying to echo or print out specific data from a DB into a string (i hope thats the right name), which should be a very simple process as I've done it before. The point is everytime a user inserts information into the database this string echo's or prints out the inserted data.
But for some very odd reason this time around when i try to echo out the data, I literally get this.
Very frustrating. As you can see from the image above i have tried using 2 different ways to do this a variable and a session, but the echo literally just prints it out. I have done this before so i am aware that it is possible. I am just a little lost into how i am meant to achieve this or even better where i went wrong. I know how to do this using a different style of coding, but i am trying to keep everything uniformed (newbie).
$addon_name = $_SESSION['Add_On_OpName'];
mysqli_report(MYSQLI_REPORT_INDEX); //overrid a common php nonsense error
$prod_sel = $dbc->query("SELECT * FROM Add_On WHERE Add_On_OpName = '$addon_name'");
$prod_sel->data_seek(0);
while ($output = $prod_sel->fetch_assoc()) {
$prod_run .= $output['Add_On_OpName'] . $output['Prod_Name'] . $output['Add_On_Price'] . $output['Add_On_Select'] . '<br>';
$addon = $output['Add_On_OpName']; //echo out product name
$_SESSION['Prod_Name'] = $output['Prod_Name']; //echo out product desc
$_SESSION['Add_On_Price'] = $output['Add_On_Price']; //echo out price
echo '
<p>$addon . " " . $_SESSION["Add_On_Price"]; </p>
';
My session is started and the php file is connected to the DB.
I also have error handling which has not given out any error messages.
You must do:
echo "<p>$addon ".$_SESSION["Add_On_Price"]."; </p>";
A string encapsulated into ' is rendered just as it is.
Use " to render a string that contains variables. Example:
$a = 3;
$a++;
echo "the result is $a";
will result in the result is 4.
On the other hand,
echo 'the result is $a';
gives the result is $a.
As the documentation points out:
Single quoted ¶ The simplest way to specify a string is to enclose it
in single quotes (the character ').
Doued ¶
If the string is enclosed in double-quotes ("), PHP will interpret
more escape sequences for special characters
Try not mix it..
And if within double quotes you have an associative array you may concat.
echo "string $variable". $array["index"];
or
echo "string $variable {$array["index"]}";
Then your code should look like
$addon_name = $_SESSION['Add_On_OpName'];
mysqli_report(MYSQLI_REPORT_INDEX); //overrid a common php nonsense error
$prod_sel = $dbc->query("SELECT * FROM Add_On WHERE Add_On_OpName = '$addon_name'");
$prod_sel->data_seek(0);
while ($output = $prod_sel->fetch_assoc()) {
$prod_run .= $output['Add_On_OpName'] . $output['Prod_Name'] . $output['Add_On_Price'] . $output['Add_On_Select'] . '<br>';
$addon = $output['Add_On_OpName']; //echo out product name
$_SESSION['Prod_Name'] = $output['Prod_Name']; //echo out product desc
$_SESSION['Add_On_Price'] = $output['Add_On_Price']; //echo out price
echo "<p>$addon {$_SESSION["Add_On_Price"]}; </p>'";
}
Long time ago
I never use double quotes due to it require parse the whole string for special notations. However it.
Try not mix single quotes with double quotes. pick up a standard for you code you will not notice any difference than is easy to code and read without surprises
You're mixing single quotes and double quotes. Single quotes do not perform interpolation of variables so when you write this:
echo '... whatever including " char and $ sign';
PHP will just literally print everything inside.
You forget some ' or " !
echo '<p>' . $addon . ' ' . $_SESSION["Add_On_Price"] . '</p>';
Use double quotes
echo "<p>$addon $_SESSION['Add_On_Price']; </p>";

PHP variable within an echo?

My WordPress site needs to have a different RSS feed on every page. In the short-term, I need to find a way to output an RSS feed with category = "2" (which will later become a number from different pages). I'm relatively new to PHP though.
Is there a way to get a variable echo'd WITHIN an echo?
I've tried:
<?php
$category = '2';
echo do_shortcode('[rssfeed cat="$category"]');
?>
and
<?php
$category = '2';
echo do_shortcode('[rssfeed cat='echo "$category"']');
?>
... But obviously they don't work. Can anyone suggest a work-around? Thanks
You can just concatenate your strings like this:
$category = '2';
echo do_shortcode("[rssfeed cat='" . $category . "']");
You can adapt your first attempt but swap the " and ' around - variables will be parsed if you use double quotes http://php.net/manual/en/language.types.string.php#language.types.string.parsing
<?php
$category = '2';
echo do_shortcode("[rssfeed cat='$category']");
?>
Variable interpolation only happens between double quotes. But shortcodes can use either single or double quotes for their attributes, so if you put your quotes the other way around, it should just work:
<?php
$category = '2';
echo do_shortcode("[rssfeed cat='$category']");
?>
The PHP string now has double quotes, so $category will be interpolated to its value, and the attribute has single quotes, which will still work fine ("Shortcode macros may use single or double quotes for attribute values"), and not terminate the enclosing PHP string.
Rizier123's answer above worked great:
<?php
$category = '2';
echo do_shortcode("[rssfeed cat='" . $category . "']");
?>
I actually needed to pull a value from each WordPress page through Advanced Custom Fields, using the_field(category). When I tried to do:
<?php
$category = the_field(category);
echo do_shortcode("[rssfeed cat='" . $category . "']");
?>
It didn't work - even though
echo $category;
produced the right value. Lots of suggested variations didn't work either - possibly this is a problem with Wordpress. I figured I needed to somehow pass a printed value of a variable into another variable, for it to work. For anyone trying to do what I was doing, a solution I found that worked is:
<?php
function abc(){
print the_field(category);
}
ob_start();
abc();
$category = ob_get_clean();
echo do_shortcode("[rssfeed cat='" . $category . "']");
?>

How do I print a character variable within quotes using php function

I need to get this output.
the result is"random"safdsaf
I am using this piece of code
<?php
$x = "random";
echo 'the result is' .$x. 'safdsaf';
?>
But i am getting this
the result israndomsafdsaf
I have to define random before printing it.
i.e. I do not want to change this piece of code
<?php
$x = "random";
What change should i make inside echo to get the desired output?
If you are using the same type of quotes delimit the quotes in your string like this:
echo "The result is\"" .$x. "\"safdsaf";
or simply use two sets of different quotes:
echo 'the result is"' .$x. '"safdsaf';
Output of either line of code:
The result is"random"safdsaf
Try this
Added the little bit space befor ' and added ", it will give the some out put as you want
echo 'the result is "' .$x. '" safdsaf';
the result will be
The result is "random" safdsaf
If you want to print out double quotes you can include them in single quotes
Something like this would do the trick.
$x = '"random"';
If for whatever reason you don't want to use single quotes you can also escape them like :
$x = "\"random\"";
As you want to keep the string, I suggest you change the original line where you put it in :
echo 'the result is"' .$x. '"safdsaf';
the principle stays the same
Here's some reading material : http://php.net/manual/en/language.types.string.php
You can use simply :-
echo 'the result is "' .$x. '" safdsaf';
OR you can use .
echo "the result is \" $x\" safdsaf";
Using the \ before the quote like this: the result is \"random\" safdsaf.
if you have alot of quotes and such in a string, i would suggest using the addslashes(). This method will do the work for you for you.
For more info, take a look here - http://www.w3schools.com/php/func_string_addslashes.asp

PHP making an URL link work inserting the $variables the right syntax way

I have this link that works.
echo '<a href="?country=Estonia&from_language=Russian&into_language=Latvian&submitted=true&
page='.$x. '">'.$x.'</a> ';
But I need the nouns Estonia, Russian and Latvian replaced by scalar variables like $country, $from_language, $into_language.
I have tried all possible combinations of dots and single and double quotes. I always get syntax errors. I don't know how the embed the variables there.
Anybody knows?
thank you
Do yourself a massive favour and use http_build_queryDocs:
<a href="?<?php echo http_build_query(array(
'country' => $country,
'fromLanguage' => $fromLanguage,
'somethingElse' => $somethingElse,
'...' => '...'
), '', '&'); ?>">Link</a>
use something easy one like sprintf or printf.
eg:
printf('<a href="?country=%s&from_language=%s&into_language=%s&submitted=true&
page=%s">%s</a>', $country, $fromLanguage, $toLanguage, $pageID, $dispText);
You could also use something like encoding with double quote sign like:
echo "<a href=\"?country={$country}&from_language={$fromLanguage}&into_language={$toLanguage}&submitted=true&
page={$pageID}\">{$dispText}</a>"
Avoid to put variables directly into string when not extremely simple. Use concatenation instead, and escape string if you want to make something good:
echo '<a href="?country=' . htmlentities($country) .
'&from_language=' . htmlentities($from_language) .
'&into_language=' . htmlentities($into_language) .
'&submitted=true&page=' . intval($x) . '">' . htmlentities($x) . '</a> ';
Anyway, if you really want it the complex way, you have to consider that you need doble quotes for HTML attributes, but double quotes are needed to wrap the PHP string because you want to put variables in it. So, you must escape HTML double quotes. Try:
echo "' . $x . ' ';
Combining the answers of Corbin and KoolKabin gives you this easy-to-read snippet:
printf('%s',
htmlspecialchars(
http_build_query(array(
'country' => $country,
'from_language' => $from_language,
'into_language' => $into_language,
'submitted' => 'true',
'page' => $x
))
),
htmlspecialchars($x));
Parametrization
printf and sprintf are very useful for adding parameters to strings. They make it easy to add escaping or complex values without making the string itself unreadable. You can always see at a glance what string it is by the first parameter.
http_build_query is also a way of parametrizing, but for the querystring. The main use is that you don't need to focus on the syntax of querystrings at all.
Escaping
htmlspecialchars makes sure that the data is fit for insertion into HTML code. It's similar to escaping in SQL queries to avoid SQL injections, only here we want to avoid HTML injections (also called XSS or cross-site scripting).
http_build_query will automatically make sure that all values are escaped for insertion as an URL in the address field in a browser. This does not guarantee fitness for insertion into HTML code. htmlspecialchars is therefore needed for the querystring as well!
If you scripts output HTML, consider to configure the output setting for argument separators arg_separator.output:
ini_set('arg_separator.output', '&');
You can then simply create the URI query info path by using http_build_query:
$country = 'de';
$fromLanguage = 'en_EN';
?>
Link
Which will give you a perfectly validly encoded output, which is immune to injections:
Link
Full Demo
$country = 'Estonia';
$from_language = 'Russian';
$into_language = 'Latvian';
echo ''.$x.' ';
OR
echo "$x";
OR
echo "{$x}";

Inserting a variable into a string in PHP

I'm putting html variable inside php var but they aren't escaped correctly so I have problem: who can help me? here here it is the code:
$var['foo'] = "<p>$coord->name</p><p>$coord->address</p>Details";
where it's the problem ?
Hmm... several errors in there, but this should work:
<?php
$var['foo'] = "<p>{$coord->name}</p><p>{$coord->address}</p>Details";
$var['foo'] = "<p>".$coord->name."</p><p>".$coord->address."</p>Details";
cheers
For working with such large strings, I favor using sprintf:
$var['foo'] = sprintf(
'<p>%s</p><p>%s</p>Details',
$coord->name,
$coord->address,
site_url($id)
);
Concatenation generally has a small performance advantage over double quotes. Also, in text editors that highlight syntax, the variables stand out better.
$var['foo'] = '<p>' . $coord->name . '</p><p>' . $coord->address . '</p>Details';

Categories