Reputation: 204
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!
Upvotes: 1
Views: 1252
Reputation: 781210
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;
}
Upvotes: 2
Reputation: 78994
utf8_encode()
takes a string. Encode each array element with array_map()
:
while ($row = mysqli_fetch_assoc($result)) {
$resArray[] = array_map('utf8_encode', $row);
}
echo json_encode($resArray);
Upvotes: 2
Reputation: 305
You can try to fetch like this by record on an array and json_encode the array where name and last_name are the names of your rows in your database
$res_array = array();
while($row = $result->mysqli_fetch_assoc()) {
$single_record = array(
"NAME_U_WANT1" => $row['NAME'],
"NAME_U_WANT2" => $row['LAST_NAME'],
);
array_push($res_array, $single_record);
}
return json_encode($res_array);
as you see you have to loop their rows
Upvotes: 2