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

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

Related

How to use echo in url

i am trying to use echo inside url. i have store data from the form in database and now i am also fetching it on my page and its working well. Now i am trying to print that data i.e. number and date in url.
Is it possible and if possible please help me out
here is my data that i am fetching and it prints the output
echo $number;
echo $yyyymmdd;
and here is my url in which i want to insert ' echo $number; ' and ' echo $yyyymmdd; ' on the place of and .
$json= file_get_contents("http://api.com/api/a2/live/apikey/fc5a69f870fdb03/number/<number>/date/<yyyymmdd>/");
I have also tried something like this but it gives error of syntex error.
$json= file_get_contents("http://api.com/api/a2/live/apikey/fc5a69f870fdb03/number/"echo $number;"/date/"echo $yyyymmdd;"/");
Another way to add changing parameters to a URL (or string) is by using sprintf(). You define your URL and a type specifier like %d as a placeholder for numbers, and %s for strings. See the php doc for the full list of type specifiers.
$urlFormat = "http://api.com/api/a2/live/apikey/fc5a69f870fdb03/number/%d/date/%s/"
^ ^
Then call sprintf with the changing parameters in order of appearance.
$url = sprintf($urlFormat, $number, $yyyymmdd);
$json = file_get_contents($url);
This becomes more convenient especially if you are calling file get contents in a loop.
Create two variables and append those two inside double-quote or single quote, depending upon the quotes which you have opened and close it.
<?php
$number=123;
$yyyymmdd='2018-10-9';
$json= file_get_contents("http://api.com/api/a2/live/apikey/fc5a69f870fdb03/".$number."/<number>/date/<".$yyyymmdd.">/");
?>
$json= file_get_contents("http://api.com/api/a2/live/apikey/fc5a69f870fdb03/number/".$number."/date/".$yyyymmdd."/");
When you compose text, you do not need "echo" but just can write variable.
You can directly use variables in double quotes like this
file_get_contents("http://api.com/api/a2/live/apikey/fc5a69f870fdb03/number/$number/date/$yyyymmdd/");
Sample code below
$number = 344;
$yyyymmdd = "20180301";
$url1 = "http://api.com/api/a2/live/apikey/fc5a69f870fdb03/number/$number/date/$yyyymmdd/";
echo "url1 ".$url1."\n";
$url2 = "http://api.com/api/a2/live/apikey/fc5a69f870fdb03/number/".$number."/date/".$yyyymmdd."/";
echo "url2 ".$url2. "\n";

Joining variable to strings fails in PHP

I'm sorry that this is basic. When I use this PHP code it works fine:
$data = '{"reportID":1092480021}';
However, when I run my URL like this:
http://localhost:8000/new/reportget.php?type=1092480021
and use this PHP code:
$reportref = $_GET['type'];
$data = '{"reportID:".$reportref."}"';
I get the error
Error_description:reportID is required
I think it's an error with how I am joining my variable to the string but I can't understand where I am going wrong.
Your string is improperly quoted. To match the format in your first example use:
$data = '{"reportID":' . $reportref.'}';
Note there are no double quotes on the last curly.
Even better:
$reportref = 1092480021;
$data = [ 'reportId' => $reportref ];
var_dump(json_encode($data));
Output:
string(23) "{"reportId":1092480021}"
For simple view and understanding, can you try out:
$data = "{\"reportID\":$reportref}";
Think that should sort it out
Use it like this
data = '{"reportID:"'.$reportref.'"}"';
It isn't working because you wrap all the value within single quote and when it come to concatenate the $reprtref you put directly .$reportref without closing the first single quote and after putting the value to concatenate you forget to open another single quote
'{"reportID:".$reportref."}"';
the correct value is
'{"reportID:"' . $reportref . '"}"';
and to match the way you specify your $data value It must be like this
'{"reportID":' . $reportref . '}';

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>";

Escaping quotes in PHP with variable

There are numerous question on Stackoverflow concerning this but I have not been able to solve this still.
I'm trying to put multiple variables inside global attribute data-*. The output should be:
data-info="23;thisWeek"
The 23 comes from a database: $row["id"], and thisWeek from a variable: $categori1.
I've tried:
echo "<tr data-info=" .fixSlashes($row["id"], $categori1); " class=\"tableclass\"><td>"
Then
<?php
function fixSlashes($idP, $categoriP){
$str = addslashes($idP . ";" .$categoriP);
return $str;
}
?>
But something goes wrong. No error message, but the behaviour is wrong. It works if I just write:
echo "<tr data-info="data-info="23;thisWeek" class=\"tableclass\"><td>"
It looks like you are not outputting the html correctly. Note the escaped quotes around the fix Slashes function. Also note the "." instead of the semicolon.
"<tr data-info=\"" .fixSlashes($row["id"], $categori1) . "\" class=\"tableclass\"><td>"
If you want to see all errors include the following code. This would have caught the semicolon error.
error_reporting(E_ALL);
ini_set('display_errors', '1');
echo "<tr data-info=" .fixSlashes($row["id"], $categori1); " class=\"tableclass\"><td>"
You have a semicolon (;) where the concat operator (.) should be. Umm, after the fixSlashes function. Before the class suffix string.
You're ending the echo statement prematurely, before the "class=\"tableclass\">" can be appended.
I hate to piggy-back, but half the answers are getting the one problem and half the answers are getting the other problem.
You need to fix your semi-colon to a period (concat) as #MingShun said.
You need to get quotes (escaped) around your data as #JimmyScray said.
echo "<tr data-info=\"" .fixSlashes($row["id"]. $categori1). "\" class=\"tableclass\"><td>";
Use escape sequence for displaying double quotations and use single quotations for id (i.e $row['id'])
echo "<tr data-info=\" $row['id'];$categori1\" class=\"tableclass\"><td>";

PHP: Complicated String With Single and Double Quotes

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);

Categories