Flutter retrieval of data broken when using session? - php

This is how i view the result from php.
final String uri =
'My PHP FILE';
Future<List<Dbjobs>> dbgetdbusers() async {
var response = await http.get(uri);
if (response.statusCode == 200) {
final items = json.decode(response.body).cast<Map<String, dynamic>>();
List<Dbjobs> dbusers = items.map<Dbjobs>((json) {
return Dbjobs.fromJson(json);
}).toList();
print(dbusers);
return dbusers;
} else {
throw Exception('Failed to load data.');
}
}
#override
Widget build(BuildContext context) {
return FutureBuilder<List<Dbjobs>>(
future: dbgetdbusers(),
builder: (context, snapshot) {
if (!snapshot.hasData)
return Center(child: CircularProgressIndicator());
return ListView(
children: snapshot.data
.map((data) => Column(
children: <Widget>[
GestureDetector(
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => JobDetails()));
},
child: Column(
children: <Widget>[
Container(
color: Colors.grey,
child: Column(
children: <Widget>[
Align(
alignment: Alignment.topLeft,
child: Text(
data.dateCreated,
style: TextStyle(fontSize: 30.0),
),
),
My Login Php
<?php
session_start();
include 'testConz.php';
$username = $_POST['Username'];
$password =md5($_POST['Password']);
$Consult = $connect -> query("SELECT * FROM tuser_ppim WHERE LoginName = '$username' and Password = '$password' ");
$Result = array();
while ($extractData=$Consult->fetch_assoc()) {
$Result[] = $extractData;
}
$ID = $Result['0']['ID'];
$_SESSION['$Consult'] = $Result;
echo json_encode($Result);
?>
>
This php file works with flutter, there are results based on the query.
<?php
session_start();
include 'testConz.php';
$Consult1=$connect->query("
SELECT * FROM tjob WHERE AssignedTo = '6';
");
$Outcome1 = array();
while ($extractData=$Consult1->fetch_assoc()) {
$Outcome1[] = $extractData;
}
echo json_encode($Outcome1);
?>
>
This one makes my screen loads with no result. any ideas?
<?php
session_start();
include 'testConz.php';
$userDetails = $_SESSION['$Consult'];
$SesID = $userDetails['0']['ID'];
$Consult1=$connect->query("
SELECT * FROM tjob WHERE AssignedTo = ".$SesID.";
");
$Outcome1 = array();
while ($extractData=$Consult1->fetch_assoc()) {
$Outcome1[] = $extractData;
}
echo json_encode($Outcome1);
echo json_encode($userDetails);
?>
>
BTW both produces the number for AssignedTo is equal 6
AND
Both produces the same result when in browser. but when it is in flutter screen the other one has no result.
Thank you!

Related

How fetch data from php mysql to flutter using post request

Hello as i am new to flutter, i want to fetch data from php api to flutter app with json data which have multiple data's in one file
my flutter code
Future<Album> fetchAlbum() async {
final response = await http.post(
Uri.parse('https://domain/folder/api.php'),
body: jsonEncode({
"description": 'description',
"naw": "homeprod",
}),
);
if (response.statusCode == 200) {
// If the server did return a 201 CREATED response,
// then parse the JSON.
return Album.fromJson(jsonDecode(response.body));
} else {
// If the server did not return a 201 CREATED response,
// then throw an exception.
throw Exception('Failed to create.');
}
}
class Album {
//final int productid;
String description;
Album({this.description = ""});
factory Album.fromJson(Map<String, dynamic> json) {
return Album(
//productid: json['product_id'],
description: json['description'],
);
}
}
this my php code on server
if($postjson['naw']=="homeprod"){
$prod = array();
$query = mysqli_query($mysqli, "SELECT * FROM product order by rand() limit 30");
while($getpost = mysqli_fetch_array($query))
{
$prod[] = array(
'description' => $getpost['description']
);
}
if($query) $result = json_encode(array('success'=>true, 'prodlists'=>$prod));
else $result = json_encode(array('success'=>false));
echo $result;
}
always flutter return with Null data type with sub type string.
Thank you in advance

load mysql to json for NVD3

<?php
$username = "root";
$password = "pw";
$host = "localhost";
$database="dbname";
$server = mysql_connect($host, $username, $password);
$connection = mysql_select_db($database, $server);
$myquery = "
SELECT `name`, `useTime`, `e_usage` FROM `electric_usage`
";
$query = mysql_query($myquery);
if ( ! $query ) {
echo mysql_error();
die;
}
$data = array();
for ($x = 0; $x < mysql_num_rows($query); $x++) {
$data[] = mysql_fetch_assoc($query);
}
echo json_encode($data);
mysql_close($server);
?>
I use upper php source to load mysql to JSON
the result of php page is
[{"name":"LED STAND","useTime":"2015-09-10 14:17:33","e_usage":"0.0599970581514709"},
{"name":"LED STAND","useTime":"2015-09-10 14:20:33","e_usage":"1.10919825898689"},
{"name":"LED STAND","useTime":"2015-09-10 14:23:33","e_usage":"1.9208018439918"}]
how to change this format to like this(for nvd3 line graph)?
function cumulativeTestData() {
return [
{
key: "LED STAND",
values: [ [ 2015-09-10 14:17:33 , 2.974623048543] ,
[ 2015-09-10 14:20:33 , 1.7740300785979]]
}
}
or theres easy way to make NVD3 line graph from mySql DB?
edit :
d3.json("./mysqljson/dbread.php", function(data) {
var dataLoad = d3.nest()
.key(function(d){return d.name})
.rollup(function(u){
return u.map(function(x){return [x.useTime,x.e_usage]})})
.entries(data);
nv.addGraph(function() {
var chart = nv.models.multiBarChart()
.x(function(d) {return d[0]})
.y(function(d) {return d[1]})
.margin({top: 50, bottom: 30, left: 40, right: 10});
chart.xAxis
.tickFormat(function(d) {
return d3.time.format('%x')(new Date(d))
});
d3.select('#mainExample')
.datum(dataLoad)
.transition().duration(500)
.call(chart);
nv.utils.windowResize(chart.update);
});
working code to use d3.json and d3.nest function
You can achieve that by using d3's d3.nest() method as follows:
Assuming your data structure as you received it using d3.json is data, then if you do:
x=d3.nest()
.key(function(d){return d.name})
.rollup(function(u){
return u.map(function(x){return [x.useTime,x.e_usage]})})
.entries(data);
Then the result would be:
{
key = "LED STAND"
values = [
["2015-09-10 14:17:33", "0.0599970581514709"],
["2015-09-10 14:20:33", "1.10919825898689"],
["2015-09-10 14:23:33", "1.9208018439918"]
]
}
I hope this helps.

Data from a single column of a sql view not displayed

I have a SQL view in phpmyadmin which has a is used to populate data in a table created using jquery jtable. The issue is quite bizarre as only one column's data which is being pulled by the view isn't being displayed and all of the others are being displayed without an issue. There is also no issue when I edit the fields and I can see the changes I made in phpmyadmin. How do I get the Successful column to display ? All help is greatly appreciated.
Screenshot of the table
js which handles creation of the table
function getLessonsLearnedResponseChildTable(ContainerID) {
var table = {
title: '',
width: '5%',
sorting: false,
edit: false,
create: false,
display: function(data) {
//create an image to be used to open child table
var $img = $('<img src="' + config.base_url + 'assets/images/expand_row-small.png" title="View Responses" style="height:30px;width:30px;cursor:pointer;" height="30" width="30"/>');
$img.click(function() {
$('#' + ContainerID).jtable('openChildTable',
$img.closest('tr'),
{
title: data.record.event,// + ' - Response Plans'
actions: {
listAction: config.base_url + "data_fetch/responses/" + data.record.risk_id,
deleteAction: config.base_url + 'data_fetch/delete_response/',
updateAction: config.base_url + 'data_fetch/edit_response/'
},
messages: defaultResponseMessages,
fields: LessonsLearnedResponseFields
}, function(data) {//opened handler
data.childTable.jtable('load');
});
});
//return image to show on row
return $img;
}
};
return table;
}
Controller method for the listAction:
function responses($risk_id = null, $offset = 0, $limit = 100, $order_by = 'response_id', $direction = 'ASC') {
$confirm_member = $this->User_model->confirm_member(true, false);
if (!$confirm_member['success']) {
$this->print_jtable_error(self::ERROR_NOT_LOGGED_IN);
return;
}
$user_id = $_SESSION['user_id'];
$this->load->model('Response_model');
$responses = $this->Response_model->get_all($risk_id, $user_id, $limit, $offset, $order_by, $direction);
if ($responses == false) {
$this->print_jtable_error(self::ERROR_NO_ACCESS_PERMISSION);
return;
} else {
return $this->print_jtable_result($responses);
}
}
get_all method in Response Model
/*
* Retrieves all responses associated with the risk
*/
public function get_all($risk_id, $user_id, $limit = null, $offset = 0, $order_by = null, $direction = 'ASC') {
//load risk model to check if user can read from project
$this->load->model('Risk_model');
if ($this->Risk_model->initialize($risk_id, $user_id) == false) {
return false;
}
if ($limit !== null && $limit != 0) {
$this->db->limit($limit, $offset);
}
if ($order_by !== null) {
$this->db->order_by($order_by, $direction);
}
$query = $this->db->select('SQL_CALC_FOUND_ROWS *', false)->from('view_responses')->where('risk_id', $risk_id)->get();
$data = $query->result_array();
$this->load->model('Task_model');
foreach ($data as &$response)
$response['WBS'] = $this->Task_model->normalize_WBS($response['WBS']);
$data['num_rows'] = $this->db->
query('SELECT FOUND_ROWS()', false)->row(0)->{'FOUND_ROWS()'};
return $data;
}
Screenshot of the sql view
successful is received but not displayed
http://imgur.com/MqCVAGm
I've been able to solve the problem. It was an issue with spelling. I had a missing c in successful coming from the SQL view and now its working fine.

MongoDB MapReduce returning null values in PHP (but works in Javascript)

I am trying to make a Map-Reduce command in PHP with exactly the same functions as in pure JavaScript and surprisingly the result is not the same. I have null values in PHP :-(
I have an "employees" collection, for each employee there is a list of "departments" to which he/she belongs.
So the Javascript map-reduce code (which works) to get the number of employees by department will be:
map = function() {
if (!this.department) {
return;
}
for (i in this.department) {
emit(this.department[i], 1);
};
};
reduce = function(key, values) {
var total = 0;
for (i in values) {
total += values[i];
};
return total;
};
retorno = db.runCommand({
"mapreduce": "employees",
"map": map,
"reduce": reduce,
"out": "employees_by_department"
});
if (retorno.ok != 1) {
print(retorno.errmsg);
};
resultado = db.employees_by_department.find();
while ( resultado.hasNext() ) {
printjson( resultado.next() );
}
And the equivalent PHP code (with null values) will be:
<?php
try {
$connection = new MongoClient( "mongodb://localhost" );
$db = $connection->selectDB("employees");
} catch (Exception $e) {
printf("Error: %s: %s\n", "Error al conectarse a MongoDB: ", $e->getMessage());
die();
}
$map = new MongoCode("function() {
if (!this.department) {
return;
}
for (i in this.department) {
emit(this.department[i], 1);
};
};");
$reduce = new MongoCode("reduce = function(key, values) {
var total = 0;
for (i in values) {
total += values[i];
};
return total;
};");
$retorno = $db->command(array(
"mapreduce" => "employees",
"map" => $map,
"reduce" => $reduce,
"out" => "employees_by_department_php"
));
if ($retorno["ok"] =! 1) {
print($retorno["errmsg"]);
}
else {
$resultado = $db->selectCollection("employees_by_department_php")->find();
foreach($resultado as $dep) {
printf("_id: \"%s\", value: %d\n", $dep["_id"], $dep["value"]);
}
}
?>
Any ideas?
UUpppss!! Solved! The problem was a typo error (a copy-paste problem) :-|
In PHP the first line of the reduce function, where it was
$reduce = new MongoCode("reduce = function(key, values) {
should be
$reduce = new MongoCode("function(key, values) {

jqgrid and server side pagination

I realize there are some related questions but I couldn't find what I was looking for. I used jqgrid many times in the past but forgot how to achieve server side pagination.
here is my javascript
$("#list").jqGrid({
url: "index.php?loadData=test",
datatype: "json",
mtype: "GET",
colNames: ["id", "eNodeB_unique", "enodeB_type", "radio_freq_mod", "macroEnbId_dec representation", "num_cells"],
colModel: [
{ name: "id", width: 55 },
{ name: "enodeB_unique", width: 90 },
{ name: "enodeB_type", width: 80, align: "right" },
{ name: "radio_freq_mod", width: 80, align: "right" },
{ name: "macroEnbId_dec_rep", width: 80, align: "right" },
{ name: "num_cells", width: 150, sortable: false }
],
pager: "#pager",
rowNum: 10,
rowList: [10, 20, 30],
sortname: "id",
sortorder: "desc",
viewrecords: true,
gridview: true,
autoencode: true,
caption: "My first grid",
loadonce:false
});
and my server side code
public function getData($page, $limit, $sidx, $sord){
$query_str = "SELECT COUNT(*) AS count FROM tbl";
$prepState = $this->DBi->prepare($query_str);
$result = $this->DBi->query($prepState);
$count = $result[0]['count'];
if( $count > 0 && $limit > 0) {
$total_pages = ceil($count/$limit);
} else {
$total_pages = 0;
}
if ($page > $total_pages){
$page = $total_pages;
}
$start = $limit * $page - $limit;
if($start < 0){
$start = 0;
}
$query_str = "SELECT * FROM tbl ORDER BY {$sidx} {$sord} LIMIT {$start}, {$limit}";
$prepState = $this->DBi->prepare($query_str);
$result = $this->DBi->query($prepState);
return $result;
}
if I keep $start and $limit in the query then i just get the inital ten results. If I take those out... then my grid shows all my results.. but there is only one page available. I have on option to click on the next page.
EDIT:
okay I realize now that I have to return this information.. I'm puzzled by the way I have to return the rows. Was JQgrid always this way?
$query_str = "SELECT * FROM enodeB ORDER BY {$sidx} {$sord} LIMIT {$start}, {$limit}";
$prepState = $this->DBi->prepare($query_str);
$result = $this->DBi->query($prepState);
$finalRows = array();
foreach($result as $row){
$finalRows[] = array('cell'=> $row);
}
return array('page' => $page, 'total' => $total_pages, 'records' => $count, 'rows' => $finalRows);
public static dynamic ToJson<T>(this IEnumerable<T> Collection, string sidx, string sord, string page, string rows, List<string> Columns)
{
return ToJson<T>(sidx, sord, page, rows, Collection, Columns);
}
private static dynamic ToJson<T>(string sidx, string sord, string page, string rows, IEnumerable<T> Collection, List<string> Columns)
{
page = page.NotNull("1"); rows = rows.NotNull("100"); sidx = sidx.NotNull("Id"); sord = sord.NotNull("asc");
int pageIndex = Convert.ToInt32(page) - 1;
int pageSize = Convert.ToInt32(rows);
int totalRecords = Collection.Count();
int totalPages = (int)Math.Ceiling((float)totalRecords / (float)pageSize);
if (!Collection.IsNull())
{
Collection = Collection.ToList().OrderWith(x => x.GetPropertyValue(sidx), sord).Skip(pageSize * pageIndex).Take(pageSize);
return JsonData<T>(Collection, totalPages, page, totalRecords, Columns);
}
return BlankJson();
}
private static dynamic JsonData<T>(IEnumerable<T> collection, int totalPages, string page, int totalRecords, List<string> Columns)
{
var colsExpr = Columns.ConvertAll<PropertyInfo>(x => Extentions.GetProperty<T>(x));
var jsonData = new
{
total = totalPages,
page = page,
records = totalRecords,
rows = collection.Select(row => new { id = row.GetPropertyValue("Id") ?? Guid.NewGuid(), cell = GetValues<T>(colsExpr, row) }),
};
return jsonData;
}
public static dynamic BlankJson()
{
return new
{
total = 0,
page = 0,
records = 0,
rows = "",
};
}
private static string[] GetValues<T>(List<PropertyInfo> columns, T obj)
{
var values = new List<string>();
try
{
foreach (var x in columns)
{
var temp = x.GetValue(obj, null);
values.Add(temp != null ? temp.ToString() : string.Empty);
}
return values.ToArray();
}
catch
{
return values.ToArray();
}
}

Categories