0

I'm creating a json array from MySql data using concat like this:

$id = '5705';
$sql = 'select concat("{""type:""colName"",""id"":""$id""}") as myJson from table where etc.;

$stmt = $conn->prepare($sql);

What's happening is, instead of getting data from colName from the table and the value of $id, I'm getting the result as it is in $sql. How do I break out of it and get colName and $id's value?

Current Result

{""type:""colName"",""id"":""$id""}

Desired Result

{""type:""novice"",""id"":""5705""}
//Here novice is data from colName, and 5705 is the value of $id
1
  • 1
    Shouldn't the desired result be: {"type":"novice","id":"5705"}? Commented Jun 8, 2013 at 14:05

3 Answers 3

3

Please DON'T DO THAT. Trying to format data into JSON in your SQL will be fragile as encoding things into JSON is subtly more tricky that you would expect and you will inevitably get it wrong.

You should use the json_encode function in PHP. It will work reliably whereas your code will almost certainly break.

$dataArray = array();

while($statement->fetch()){
    $data = array();
    $data['type'] = $typeColumn;
    $data['id'] = $id;

    $dataArray[] = $data;
}

json_encode($dataArray, JSON_HEX_QUOT);

Also, formatting data to send to a client really shouldn't be part of an SQL query.

Sign up to request clarification or add additional context in comments.

3 Comments

This is the way we currently do it.
Then why are you moving it into the SQL ?
Ha! We group_concat complete xml structures directly from mysql. Don't let him scare you...
1

You need a better concatenation either in query and php

'select concat("{""type:"",colName,"",""id"":""'.$id.'""}") 

Despite it is not really needed you could surround column name with backticks `

3 Comments

Ok. So the $id part works, but it's still the same with colName. I still get {"type:",colName,","id":"5705"}
@Norman try this "select concat('{\"\"type:\"\",colName,\"\",\"\"id\"\":\"\"".$id."\"\"}') form where "
Ok. I got it to work. You need to do it like this: 'select concat("{""type:",colName,",""id"":""'.$id.'""}") -> remove the " before and after colName.
0

Your variables inside your string are not substituted with their values, as you got single quotes. Double quoted strings will expand variables with their values

Thus, you could invert your quotes, like this, in order to get the actual values of your variables:

$sql = "select concat('...')"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.