Joining variable to strings fails in PHP - 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 . '}';

Related

How do I remove quotation from csv?

How do I remove quotation from csv?
Code
use Goutte\Client;
$client = new Client();
$response = $client->request('GET', 'http://c-manage.herokuapp.com/login');
$login_form = $response->filter('form')->form();
$login_form["account"] = '1';
$login_form["password"] = 'rpa1001';
$client->submit($login_form);
$client->request('GET', 'http://c-manage.herokuapp.com/client/download?searchQuery%5Bstatus%5D=1&searchQuery%5BregisterStartDate%5D=2010-01-01&searchQuery%5BregisterEndDate%5D=2020-01-01');
$csvResponse = $client->getResponse()->getContent();
return $csvResponse;
response is ...
ID,ステータス,分類,名前,名前(カナ),誕生日,郵便番号,住所,メールアドレス,電話番号,FAX,メモ,登録日,更新日\r\n
213,契約中,個人,"鶴田 秀夫","ツルタ ヒデオ",2000/07/24,1508207,神奈川県吉田市北区佐々木町小林7-4-5,hiroshi.nakatsugawa#yamaguchi.net,0310-282-609,0730-327-581,,"2010-01-25 00:00:
00","2010-01-25 00:00:00"\r\n
221,契約中,個人,"桑原 彩羅","クワハラ サイラ",2008/04/03,8103797,青森県杉山市西区石田町浜田3-4-10,vwakamatsu#kiriyama.jp,090-5710-4350,03849-5-5746,,"2010-01-09 00:00:00","2010-0
1-09 00:00:00"\r\n
237,契約中,個人,"堤 悟志","ツツミ サトシ",2001/04/29,6875750,栃木県佐々木市東区中島町浜田6-6-6,xtsuda#suzuki.com,022-557-4260,0573-01-2822,,"2010-02-07 00:00:00","2010-02-07 00:0
0:00"\r\n
273,契約中,個人,"富永 圭三","トミナガ ケイゾウ",2003/03/16,6314524,静岡県若松市東区廣川町青山10-9-6,yamaguchi.takuma#kondo.com,0020-062-493,06-3862-0779,,"2010-02-13 00:00:00","2
010-02-13 00:00:00"\r\n
.
.
.
What I want to do
I want to remove quotation from csv.
not
213,契約中,個人,"鶴田 秀夫","ツルタ ヒデオ",2000/07/24,1508207,
but
213,契約中,個人,鶴田 秀夫,ツルタ ヒデオ,2000/07/24,1508207,
※This personal information is fake.
What I did
str_replace(""", "", $csvResponse);
str_replace("\xEF\xBB\xBF", '', $csvResponse);
but, not working
The quotes serve a purpose here so you shouldn't be removing them haphazardly. The quotes prevent columns from breaking when they need to contain text that can also contain the delimiter. Like "Foo, bar, baz" for example. Removing the quotes turns this one column into 3 columns, which is obviously wrong.
Though, if you did want to remove them str_replace would certainly not be the way to go, because the quotes can be escaped to be literals inside the column. For example, using str_replace on this column: "He said \"this is crazy\", and left." would strip literals from the column value.
Instead you should load the CSV data with fgetcsv() or str_getcsv() and rebuild the CSV without the quotes like so...
foreach (str_getcsv($csvData) as $row) {
echo implode(",", $row), "\n";
}
This will give you back the literal values of each row without the quotes. Though any literal quotes inside those values will become quotes.

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

redirecting to a URL query string

I am trying to redirect a page to:
product_page.php?rest_id=$rest_id&area=$rest_city
for example:
product_page.php?rest_id=3&area=Enfield
At the moment the page is redirecting to:
http://localhost/PhpProject2/product_page.php?rest_id=&area=
Even though i have specified :
if (isset($_GET['rest_id'])){
$rest_id = mysqli_real_escape_string($dbc,$_GET['rest_id']);
}
if (isset($_GET['area'])){
$area = mysqli_real_escape_string($dbc,$_GET['area']);
}
if (isset($_GET['add_item'])) {
(int)$_GET['add_item']]){
$_SESSION['Shopping_cart_' . (int) $_GET['add_item']]+='1';
//redirect
echo"<script>window.open('product_page.php?rest_id=$rest_id&area=$rest_city','_self')</script>"; //header does not work
}
How would i go about getting the echo to re-direct to the correct page.
What i have tried:
Calling both add_item, rest_id and rest_city in the same if asset.
Moving the $_GET rest_id and rest_city closing tag after the echo.
The two above options just stop the page from re-directing all together, this is my first time doing this, any suggestions or tips would be greatly appreciated.
You should use double qotes ["string $variable string"] for variable to work inside a string or if not you should concatenate the string with [.] sign.
echo"<script>window.open('product_page.php?rest_id=$rest_id&area=$rest_city','_self')</script>";
This will not work because of single qoute [']
Regards
There are many syntax errors in your code. Also, the way you echo the string is wrong. You need to concat the variables with the string, using the PHP concatenation operator, else use double quotes.
Below fixed your errors:
if (isset($_GET['rest_id'])){
$rest_id = mysqli_real_escape_string($dbc,$_GET['rest_id']);
}
if (isset($_GET['area'])){
$area = mysqli_real_escape_string($dbc,$_GET['area']);
}
if (isset($_GET['add_item'])) {
$_SESSION['Shopping_cart_'] = (int) $_GET['add_item']+='1';
echo"<script>window.open('product_page.php?rest_id=" . $rest_id . "&area=" . $rest_city . "','_self')</script>";
}

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 preg_replace problem

This is a follow-up question to the one I posted here (thanks to mario)
Ok, so I have a preg_replace statement to replace a url string with sometext, insert a value from a query string (using $_GET["size"]) and insert a value from a associative array (using $fruitArray["$1"] back reference.)
Input url string would be:
http://mysite.com/script.php?fruit=apple
Output string should be:
http://mysite.com/small/sometext/green/
The PHP I have is as follows:
$result = preg_replace('|http://www.mysite.com/script.php\?fruit=([a-zA-Z0-9_-]*)|e', ' "http://www.mysite.com/" .$_GET["size"]. "/sometext/" .$fruitArray["$1"]. "/"', $result);
This codes outputs the following string:
http://mysite.com/small/sometext//
The code seems to skip the value in $fruitArray["$1"].
What am I missing?
Thanks!
Well, weird thing.
Your code work's perfectly fine for me (see below code that I used for testing locally).
I did however fix 2 things with your regex:
Don't use | as a delimiter, it has meaning in regex.
Your regular expression is only giving the illusion that it works as you're not escaping the .s. It would actually match http://www#mysite%com/script*php?fruit=apple too.
Test script:
$fruitArray = array('apple' => 'green');
$_GET = array('size' => 'small');
$result = 'http://www.mysite.com/script.php?fruit=apple';
$result = preg_replace('#http://www\.mysite\.com/script\.php\?fruit=([a-zA-Z0-9_-]*)#e', ' "http://www.mysite.com/" .$_GET["size"]. "/sometext/" .$fruitArray["$1"]. "/"', $result);
echo $result;
Output:
Rudis-Mac-Pro:~ rudi$ php tmp.php
http://www.mysite.com/small/sometext/green/
The only thing this leads me to think is that $fruitArray is not setup correctly for you.
By the way, I think this may be more appropriate, as it will give you more flexibility in the future, better syntax highlighting and make more sense than using the e modifier for the evil() function to be internally called by PHP ;-) It's also a lot cleaner to read, IMO.
$result = preg_replace_callback('#http://www\.mysite\.com/script\.php\?fruit=([a-zA-Z0-9_-]*)#', function($matches) {
global $fruitArray;
return 'http://www.mysite.com/' . $_GET['size'] . '/sometext/' . $fruitArray[$matches[1]] . '/';
}, $result);
i write it again, i don't understand good where is the error, the evaluation of preg results is very weird in php
preg_replace(
'|http\://([\w\.-]+?)/script\.php\?fruit=([\w_-]+)|e'
, '"http://www.$1/".$_GET["size"]."/sometext/".$fruitArray["$2"]."/";'
, $result
);
It looks like you have forgotten to escape the ?. It should be /script.php\?, with a \? to escape properly, as in the linked answer you provided.
$fruitArray["\$1"] instead of $fruitArray["$1"]

Categories