Elye
Elye

Reputation: 60351

MySQL Field contain newline, how to extract through PHP with new line?

Currently one of the field in MySQL db contains something as below

PARTICIPATE

These are a few areas which would greatly improve with your participation

i.e. There's two new lines.

However, when extracted from Json, it became something as below, where the new line is missing.

{Description: "PARTICIPATE These are a few areas which would greatly improve with your participation"}

My PHP code as below

function queryPrintJson($cnx, $query) {
    $rows=queryReturnJsonArray($cnx, $query);
    print json_encode($rows);
}

function queryReturnJsonArray($cnx, $query) {
    $result=mysqli_query($cnx, $query) or die ("Can't execute query!");
    $rows = array();

    while($obj = $result->fetch_object()){
        $rows[] = $obj;
    }
    $result->close();
    return $rows;
}

Is there anyway I could be preserve the newline? I'm okay if it gets converted to \\n.

Upvotes: 0

Views: 99

Answers (1)

RiggsFolly
RiggsFolly

Reputation: 94682

You could replace all newlines with <br> for the column in question in the PHP as its ultimately going to be HTML when it gets to the javascript code like this.

function queryReturnJsonArray($cnx, $query) {
    $result=mysqli_query($cnx, $query) or die ("Can't execute query!");
    $rows = array();

    while($obj = $result->fetch_object()){
        $obj->col_name = str_replace("\n", '<br>', $obj->col_name);
        $rows[] = $obj;
    }
    $result->close();
    return $rows;
}

Upvotes: 1

Related Questions