Jimmy
Jimmy

Reputation: 12487

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.

Upvotes: 0

Views: 74

Answers (4)

Diogo Santo
Diogo Santo

Reputation: 789

For simple view and understanding, can you try out: $data = "{\"reportID\":$reportref}";

Think that should sort it out

Upvotes: 2

Yves Kipondo
Yves Kipondo

Reputation: 5603

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 . '}';

Upvotes: 1

msg
msg

Reputation: 8161

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

Upvotes: 3

shakogele
shakogele

Reputation: 399

Use it like this

data = '{"reportID:"'.$reportref.'"}"';

Upvotes: 1

Related Questions