简体   繁体   中英

Creating a json array using concat with MySql

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

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.

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 `

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('...')"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM