I am converting SQL table rows into JSON, with the help of PHP, MySQLi and json_encode.
My present code approach is -
<?php
error_reporting(0);
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "my_db";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if(isset($_GET['from'])) {
$from = $_GET['from'] - 1;
} else {
$from = 0;
}
if(isset($_GET['count'])) {
$count = $_GET['count'];
} else {
$count = 10000;
}
$sql = "SELECT * FROM `my_table` Limit $from, $count";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
$resultArray = array();
$tempArray = array();
while ($row = $result->fetch_assoc()) {
$tempArray = $row;
array_push($resultArray, $tempArray);
}
//var_dump($resultArray);
$json = json_encode($resultArray);
} else {
$json = '{"Json_Result":"Record NOT found!"}';
}
print($json);
$conn->close();
This works fine, if the data retrieved from table is in correct format. But, unfortunately some of my rows contain some special characters, which were not converted into proper format at the inserting. This code fails if it encounters any of such rows. On using var_dump
, I found that those special characters are seen as �
.
On searching about issue, I found out that, for json_encode
to be working, all characters must be in utf8
format. But, I am unable to figure out, how should I implement it here, before using json_encode
?