Exception has occurred flutter - php

I have a method to read the data from the database. The code is completely working, but there is a problem, it is if I run the code and there is no data in the database, I get the error:
E/flutter (29414): [ERROR:flutter/lib/ui/ui_dart_state.cc(177)] Unhandled Exception: FormatException: Unexpected character (at character 1)
E/flutter (29414): No Data Found.
E/flutter (29414): ^
And my code:
Future<List<data>> FetchT() async {
apiURL = 'https://*******.com/getList.php?C=' +
gatName.toString();
var response = await http.get(apiURL);
if (response.statusCode == 200) {
final items = json.decode(response.body).cast<Map<String, dynamic>>();
List<data> listOfFruits = items.map<data>((json) {
return data.fromJson(json);
}).toList();
return listOfFruits;
} else {
//throw Exception('Failed to load data from Server.');
}
}
PHP code:
<?php
include 'connt.php';
$C= $_GET["C"];
$sql = "SELECT * FROM top WHERE C=? ORDER BY id DESC ";
$result = $con->query($sql);
$stmt = $con->prepare($sql);
$stmt->bind_param("s",$C);
$stmt->execute();
$result = $stmt->get_result();
if ($result->num_rows >0) {
while($row[] = $result->fetch_assoc()) {
$item = $row;
$json = json_encode($item, JSON_NUMERIC_CHECK);
}
} else {
echo "No Data Found.";
}
echo $json;
$con->close();
?>
I previously searched the old topics here and tried all the topics and problems similar to mine, but I did not find a solution to my problem.
How can I solve this problem?

You didn't specify the header code if no data is found.
You should change your php code to this:
<?php
include 'connt.php';
$C= $_GET["C"];
$sql = "SELECT * FROM top WHERE C=? ORDER BY id DESC ";
$result = $con->query($sql);
$stmt = $con->prepare($sql);
$stmt->bind_param("s",$C);
$stmt->execute();
$result = $stmt->get_result();
if ($result->num_rows >0) {
while($row[] = $result->fetch_assoc()) {
$item = $row;
$json = json_encode($item, JSON_NUMERIC_CHECK);
}
} else {
http_response_code(404);
$json = json_encode(["error" => "No Data Found."]);
}
echo $json;
$con->close();
?>

Related

I created the code using mysqli_fetch_assoc with 'while' , but it's not woking

I created the code using mysqli_fetch_assoc with 'while' as shown below.
But it does not work.
if ($ result = mysqli_query ($ dbconn, $ query)) {
It works by here.
while ($ row = mysqli_fetch_assoc ($ result)) {
It does not work from here.
I can not find the wrong part.
If I do not use 'while', it works as follows.
What is the problem?
// not works
$query = "select * from member where f_status='1'";
if ($result=mysqli_query($dbconn, $query)) {
while ($row = mysqli_fetch_assoc($result)) {
if ($row[f_status]==0) {
error("No data");
} else {
echo $row[f_user_id];
echo $row[f_user_name];
}
}
mysqli_free_result($result);
}
// works
$query = "select * from member where f_status='1'";
$result = mysqli_query($dbconn, $query);
$row = mysqli_fetch_assoc($result);
if ($row) {
echo $row[f_user_id];
echo $row[f_user_name];
} else {
error("No data");
}
I think the problem is the way you have iterated while loop and condition to show No data message,
You should try this way:
$query = "select * from member where f_status='1'";
if ($result = mysqli_query($dbconn, $query)) {
if ($result->num_rows) {
while ($row = mysqli_fetch_assoc($result)) {
echo $row[f_user_id];
echo $row[f_user_name];
}
}
else {
error("No data");
}
mysqli_free_result($result);
}
Hope this should solve your issue.

PHP json_encode doesn't print anything

I'm running PHP and MySQL and have the following code:
$data = array();
$result = mysql_query($search_query);
if ($result){
while($row = mysql_fetch_assoc($result)) {
$data[] = $row;
}
if (sizeof($data) > 0) {
//var_dump($data);
echo json_encode($data);
} else {
echo 'empty';
}
}
If my query has no rows I do get empty returned.
But if there's any records I get a Resource has no content in Safari.
But if I uncomment my //var_dump($data); then I do get a nice array of values.
Try this:
// Database connection.
$mysqli = new mysqli('localhost', 'user', 'password', 'db_name');
// Your query.
$search_query = "SELECT * FROM yuor_table";
$data = array();
$result = $mysqli->query($search_query);
if ($result){
while($row = $result->fetch_assoc()) {
$data[] = $row;
}
if (sizeof($data) > 0) {
//var_dump($data);
echo json_encode($data);
} else {
echo 'empty';
}
}
This is very simple solution. I would suggest to use "mysqli".

Show all users whose status is "user" or "admin" on the list

I have an issue to get users data by their status (Admin/User).
I don't want to show an admin on the list, so help me...
$status= 'user';
// I've tried this, but it didn't helped
$sql = "SELECT * FROM users WHERE status = $status";
$result = $conn->query($sql);
if ($result->num_rows >0) {
while($row[] = $result->fetch_assoc()) {
$tem = $row;
$json = json_encode($tem);
}
} else {
echo "Error";
}
echo $json;
$conn->close();
}
?>
You need to put $status in the single quotation marks
if
$status = 'user';
then:
$sql = "SELECT * FROM users WHERE status = '$status'";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
$json = json_encode($row);
}
} else {
echo "Error";
}
echo $json;
$conn->close();
}
?>

JSON API in PHP

My android developer require JSON response like below.
[
{ "StudentId":"1", "StudentName":"Rahul", "StudentMarks":"83" }, { "StudentId":"2", "StudentName":"Rohit", "StudentMarks":"91"} ]
My current code for generate JSON API is like below.
<?php
$response = array();
require 'db.php';
$query = "SELECT * FROM news order by id desc";
$result = mysqli_query($conn,$query);
if (mysqli_num_rows($result) > 0) {
$response["news"] = array();
while ($row = $result->fetch_assoc()) {
$news= array();
$news["id"] = $row["id"];
$news["title"] = $row["title"];
$news["description"] = $row["description"];
array_push($response["news"], $news);
}
$response["success"] = 1;
// echoing JSON response
echo json_encode($response);
} else {
$response["success"] = 0;
echo json_encode($response);
}
I am getting response like below
{"news":[{"id":"1","title":"My first news title here","description":"My first news description will be here"}],"success":1}
I have tried lot of changes but not getting proper result like above. I want remove "news" and "success" from my response for make it as required response. What should I change for get response like first located code ?
Thanks
Try this code
<?php
$response = array();
require 'db.php';
$query = "SELECT * FROM news order by id desc";
$result = mysqli_query($conn,$query);
if (mysqli_num_rows($result) > 0) {
$response["news"] = array();
while ($row = $result->fetch_assoc()) {
$arr[]=array('StudentId'=>$row["id"],'title'=>$row["title"],'description'=>$row["description"])
}
$response =$arr ;
// echoing JSON response
echo json_encode($response);
} else {
$response = array('success'=>0);
echo json_encode($response);
}

Run php action for every element

I have a php script which retrieves data from mysql db.
Everything works fine, but my problem is that this $result = $dao->joinedEvents($userId); returns an array of numbers and what I would like to do is to run this $secondResult = $dao->joinedEventsInfo($receivedIds); for every ID and this script I'm using right now returns data only for one ID.
This is part of my php script:
$userId = htmlentities($_REQUEST["userId"]);
$result = $dao->joinedEvents($userId); //This is getting the IDs array
if(!empty($result)) {
$receivedIds = $result["event_id"];
$ids = explode(",", $receivedIds);
foreach($ids as $id){
$secondResult = $dao->joinedEventsInfo($id);
if(!empty($secondResult)) {
$returnValue["finalResult"][] = $secondResult;
} else {
$returnValue["status"] = "error";
$returnValue["message"][] = "Could not find records for id" . $id;
}
}
} else {
$returnValue["status"] = "Empty error";
$returnValue["message"] = "Could not find records";
}
$dao->closeConnection();
echo json_encode($returnValue);
And this is joinedEvents script:
public function joinedEvents($userId){
$returnValue = array();
$sql = "SELECT event_id from MyTable WHERE userId= '$userId' LIMIT 0 , 30";
$statement = $this->conn->prepare($sql);
if (!$statement)
throw new Exception($statement->error);
$statement->execute();
$result = $statement->get_result();
while ($myrow = $result->fetch_assoc())
{
$returnValue[] = $myrow;
}
return $returnValue;
}
This is joinedEventsInfo script:
public function joinedEventsInfo($eventId){
$returnValue = array();
$sql = "SELECT * FROM Events WHERE eventId = '$eventId' LIMIT 0 , 30";
$statement = $this->conn->prepare($sql);
if (!$statement)
throw new Exception($statement->error);
$statement->execute();
$result = $statement->get_result();
while ($myrow = $result->fetch_assoc())
{
$returnValue[] = $myrow;
}
return $returnValue;
}
Edit: Tha reason I need this is that I have two tables. In the first one I have just IDs and in the second one I have info. So first I need to get the IDs and then I need to get data for every ID I have just received.
Thank you very much , I'm totally stuck.
Based on the updated code snippets and the discussion below, it is found that $result is indeed an array, and the solution is:
$userId = htmlentities($_REQUEST["userId"]);
$result = $dao->joinedEvents($userId);
if(count($result)){
foreach($result as $array){
$event_id = $array['event_id'];
$secondResult = $dao->joinedEventsInfo($event_id);
if(!empty($secondResult)) {
$returnValue["finalResult"][] = $secondResult;
} else {
$returnValue["status"] = "error";
$returnValue["message"][] = "Could not find records for id: " . $event_id;
}
}
}else {
$returnValue["status"] = "Empty error";
$returnValue["message"] = "Could not find records";
}
$dao->closeConnection();
echo json_encode($returnValue);
Have you tried array_map()?
That would allow you to call a php function on each member of an array easily.
Another way would be to use the common while ($row = mysql_fetch_array($result)) which would execute the code in the while loop for each row of your returned results. Note, you will likely have to change the mysql_fetch_array to something specific for your SQL connection.

Categories