Creating an array (which I want to encode to JSON) from a MySql select query, but one of the query columns has free text entered by users. I don't want special characters (or 'n/' formatting) in this column preventing the array from populating correctly. Not all rows are being displayed by the current statement and 'n/' etc characters are being included:
echo json_encode($data); //not sure this is in the right part of my code
I've used the below code successfully before but not in an array:
echo nl2br($row['MessageText'],ENT_COMPAT|ENT_IGNORE, "UTF-8");
My PHP code:
if(!empty($_POST['msg']))
{
$userid = session_id();
$searchStr = get_post($con,'msg');
$aKeyword = explode(" ", $searchStr);
$aKeyword = array_filter($aKeyword); // Remove empty values
$stmt = $con->prepare(
'SELECT
a.ID, a.MessageText, a.cntLikes, IFNULL(b.Type,0) as Type
FROM
(
SELECT m.ID, m.MessageText,count(l.Id) as cntLikes
FROM MessageMain m
LEFT OUTER JOIN Likes l on m.ID = l.PostID
WHERE MessageText REGEXP ?
GROUP BY m.ID, m.MessageText ORDER BY count(m.id) desc
)a
LEFT OUTER JOIN
(
SELECT postId, COUNT(*) as type
FROM likes
WHERE userid = ?
GROUP BY postId
)b
on a.Id = b.PostId'
);
$regexString = implode('|', $aKeyword);
$stmt->bind_param('ss',$regexString, $userId);
$stmt->execute();
$result = $stmt->get_result();
$data = array();
if(mysqli_num_rows($result) > 0) {
While($row = $result->fetch_assoc()) {
$data = $row;
echo json_encode($data);
}
}
}
What solved the issue was amending:
$data = $row;
to:
$data[] = array ( 'ID' => $row['ID'], 'UserID' => $row['UserID'], 'MessageText' => nl2br(htmlentities($row['MessageText'],ENT_COMPAT|ENT_IGNORE, "UTF-8") ), 'cntLikes' => $row['cntLikes'], 'Type' => $row['Type'] );
The database column that was stopping the array from pulling back was 'MessageText'. This column had originally come from an Excel spreadsheet where the data was very dirty.
Using
nl2br(htmlentities($row['MessageText'],ENT_COMPAT|ENT_IGNORE, "UTF-8"))
resolved the issue.
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.