Frank Frank - 5 months ago 20
JSON Question

Getting JSON from PHP MySQL connection

There are many examples of this on StackOverflow, but I can't see the error in my code. I followed a few tutorials and copied some code off this forum and it still errors bugs out.

My

CREATE TABLE
query:

CREATE TABLE `e1_ENGLISH` (
`entry_id` int(11) NOT NULL AUTO_INCREMENT,
`words_e1` char(30) NOT NULL,
`date` date DEFAULT NULL,
`phonetic_e1` varchar(50) NOT NULL,
PRIMARY KEY (`entry_id`)
) ENGINE=InnoDB AUTO_INCREMENT=42 DEFAULT CHARSET=utf8mb4


My PHP code:

<?php
// establish connection
// mysqli contect (host, user, pass, db)
$conn = mysqli_connect("localhost","androidapp","password","myDB");

// check for connection success
if(!$conn) {
die("Error, could not connect: " . mysqli_connect_error());
}

// build query
$sql = "SELECT * FROM e1_ENGLISH";
$result = mysqli_query($conn, $sql); // fetch data

// convert result to array
$resArray = array();
while ($row = mysqli_fetch_assoc($result)) {
//$resArray[] = $row;
$resArray[] = utf8_encode($row);
}

// display result
echo json_encode($resArray);

// close connection
mysqli_close($conn);
?>


The output I get (with
utf8_encode
):

[null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null]


I get a blank screen with just
$resArray[] = $row;


I am new to PHP, MySQL data, and webservers. Any mistakes you can spot? Additionally, I dont have a script or anything, this is straight PHP.

Thank you in advance!

Answer

The argument to utf8_encode() has to be a string, you can't call it on an array. You need to loop over $row calling it on each element.

$resArray = array();
while ($row = mysqli_fetch_assoc($result)) {
    foreach ($row as &$val) {
        $val = utf8_encode($val);
    }
    $resArray[] = $row;
}