List online users and get total "talep" count each user - php

I have a table for Talepler and Yonetim. Now Each talepler has his own users. and each user is mapped to that talepler by a field called user id. So how i can print out online users with total count in Talepler table by Count(*) with Join query.
Here my code with helper function. But i want with join.
$this->db->select('yonetim.id, yonetim.user, yonetim.onoff');
$this->db->from('yonetim');
$this->db->where('yonetim.onoff',1);
$query = $this->db->get();
$datam = array();
foreach ($query->result() as $data) {
$count = checkIfuserMax($data->id);
if($talepsay < 10 ) {
$datam[] = array(
'id' => $data->id,
'user' => $data->user,
'onoff' => $data->onoff,
'toplamtalep' => $count
);
}
}
echo json_encode($datam);
and here my helper function
function checkIfuserMax($id) {
$ci =& get_instance();
$ci->db->select('COUNT(*) as toplam');
$ci->db->where(array( 'hangiadmin' => $id, 'onaylayan' => null));
$ci->db->from('talepler');
$query = $ci->db->get();
$result = $query->result();
return $result[0]->toplam;
}
Finally here my json result
[
{
"id": "1",
"user": "user1",
"onoff": "1",
"toplamtalep": "13"
},
{
"id": "2",
"user": "user2",
"onoff": "1",
"toplamtalep": "0"
},
{
"id": "4",
"user": "user3",
"onoff": "1",
"toplamtalep": "2"
},
{
"id": "173",
"user": "user4",
"onoff": "1",
"toplamtalep": "6"
}
]
This code working properly. But i want to make this same result with "JOIN" query. Could you please help me about this query?

Related

Nested array in json data in php

I need to show Mysql data in json nested array like
{
"status": true,
"categories": [
{
"id": "1",
"title": "Title 1",
},
{
"id": "2",
"title": "Title 2",
},
{
"id": "3",
"title": "Title 3",
}
]
}
Code I am trying is
$sql = "SELECT * FROM `categories`";
$res_data = mysqli_query($conn,$sql);
$rows = array();
while($row = mysqli_fetch_array($res_data)){
$rows[] = $row;
foreach($rows as $row){
$rows = ['id' => $row['id'], 'title' => $row['title']];
}
}
$data = array('status' => true, 'categories' => array($rows));
echo json_encode($data);
But what I get is only with one record in the nested array i.e
{
"status": true,
"categories": [
{
"id": "1",
"title": "Title 1",
}
]
}
How can I achieve my requirement?
If you want to avoid duplication, leave out the foreach loop and just write in the while loop:
$rows[] = ['id' => $ row ['id'], 'title' => $ row ['title']];
…because with the while loop, you already run through the row array.
You don't need any loops. Mysqli already returns a nested array which you can directly output to JSON
$res_data = $conn->query("SELECT id, title FROM `categories`")
echo json_encode(['status' => true, 'categories' => $res_data->fetch_all(MYSQLI_ASSOC)]);

PHP One To Many

I Have 2 Table. 1 Table Questions, 1 Table Answers.
I Need 1 Questions in 4 Answers.
Because I create a web application for students.
I want this JSON
[
{
"id": "1",
"question": "Türkiye'nin Başkenti Neresidir?",
"answers": [
{
"id": "1",
"answer": "Ankara",
"query": "1"
},
{
"id": "2",
"answer": "Istanbul",
"query": "0"
}
]
}
],
Postman
[
{
"id": "1",
"question": "Türkiye'nin Başkenti Neresidir?",
"answers": {
"id": "1",
"answer": "Ankara",
"query": "1"
}
},
{
"id": "1",
"question": "Türkiye'nin Başkenti Neresidir?",
"answers": {
"id": "2",
"answer": "İstanbul",
"query": "0"
}
},
]
PHP Code
public function GetQuestions($AppID){
$QuestionArray = [];
$Select = $this -> DBConnect -> prepare("SELECT questions.id, questions.question, answers.id AS answerid, answers.answer AS answer,answers.query AS query FROM questions INNER JOIN answers ON questions.id = answers.questionid WHERE active = 1 AND appid = ".$AppID);
$Select -> execute();
$Questions = $Select -> fetchAll(PDO::FETCH_ASSOC);
foreach($Questions as $Item){
$QuestionArray[] = Array(
'id' => $Item['id'],
'question' => $Item['question'],
'answers' => Array(
'id' => $Item['answerid'],
'answer' => $Item['answer'],
'query' => $Item['query']
)
);
}
return $JSON = json_encode($QuestionArray, JSON_UNESCAPED_UNICODE);
}
Please try this procedure.
public function GetQuestions($AppID)
{
$QuestionArray = [];
$Select = $this->DBConnect->prepare('SELECT questions.id, questions.question, answers.id AS answerid, answers.answer AS answer,answers.query AS query FROM questions INNER JOIN answers ON questions.id = answers.questionid WHERE active = 1 AND appid = '.$AppID);
$Select->execute();
$Questions = $Select->fetchAll(PDO::FETCH_ASSOC);
foreach ($Questions as $Item) {
if (!array_key_exists($Item['id'], $QuestionArray)) {
$QuestionArray[$Item['id']] = array(
'id' => $Item['id'],
'question' => $Item['question'],
'answers' => array(),
);
}
$QuestionArray[$Item['id']]['answers'][] = array(
'id' => $Item['answerid'],
'answer' => $Item['answer'],
'query' => $Item['query'],
);
}
return $JSON = json_encode($QuestionArray, JSON_UNESCAPED_UNICODE);
}
This is my idea, you can reference and update with your cases.
GetQuestions
public function GetQuestions($appID) {
// TODO
// $quest_result = Get form DB;
foreach ($quest_result as $quest) {
$quest_response[id] = $quest[id];
$quest_response[quest] = $quest[question];
$quest_response[answers] = getAnswerByQuestId ($quest[id]);
}
return $quest_response;
}
getAnswerByQuestId
public function getAnswerByQuestId(questionID) {
// TODO
// $array_answer = Get form DB;
return $array_answer;
// ex:
// return array_answer[
// "id": "1",
// "answer": "Ankara",
// "query": "1"
//]
}

Codeigniter combine two array in foreach loop

I have problem to combining two array, here my sample code
$arr1 = [];
$data = $this->db->query("SELECT QUERY");
foreach ($data->result_array() as $row) {
$arr1[] = array(
"type" => "column",
"name" => $row['name'],
"legendText" => $row['name'],
"showInLegend" => true
);
}
$count = $this->db->query("SELECT QUERY");
foreach ($count->result_array() as $rows) {
$arr1[]["dataPoints"] = array(
"label" => $rows['data']
);
}
With this code, result is
[
{
"type": "column",
"name": "LA 1",
"legendText": "LA 1",
"showInLegend": true
},
{
"dataPoints": {
"label": "1"
}
}
]
I want to combine two array, So the output should be like this:
[
{
"type": "column",
"name": "LA 1",
"legendText": "LA 1",
"showInLegend": true,
"dataPoints": [{
"label": "1"
}]
}
]
Please someone help me to find out the easiest way to solve this issue.
The proper way to fix this would be to change your database queries to one which would return all the information in a single query.
$data = $this->db->query("SELECT a.*, b.datapoints FROM table1 a, table2 b....");

How to get the values only absent date and absent student id

Here i am doing one attendance module , that means who all are absent, i stored their id in database as json string ,here actually id 1 is absent on 2017-04-11 and 2017-04-12
id 2 is absent 2017-04-11 and 2017-04-13,upto now working fine, here after what i want to do means , i have one dynamic variable like loginId=2, i want to display the results like id 2 is which are the date he is absent, please see below my expected results.
student_absent_list (table name)
absendId studentAbsentId studentAbsentDate schoolId
1 ["1","2"] 2017-04-11 2
2 ["1"] 2017-04-12 2
3 ["2"] 2017-04-13 2
My Controller
public function getAbsentListStaff()
{
date_default_timezone_set('Asia/Kolkata');
$loginType = $_POST['loginType'];
if($loginType == 1)
{
$data = array(
"schoolId" => $_POST['schoolName'],
"classId" => $_POST['className'],
"sectionId" => $_POST['sectionName'],
"loginId" =>$_POST['loginId'],
);
$absentresponse= $this->Android_login_model->admin_options_listdisplayparent($data);
foreach ($absentresponse as $key => $value)
{
$absentresponse[$key]->studentAbsentId= json_decode($value->studentAbsentId,true);
}
if($absentresponse){
$return=array('status'=>"Success",'data'=>$absentresponse);
echo json_encode($return);
}
else{
$return=array('status'=>"Error",'description'=>"Data Not Found");
echo json_encode($return);
}
}
}
My Model
public function admin_options_listdisplayparent($params)
{
$this->db->select('*');
$this->db->where('status !=', '1');
$this->db->where('schoolId =',$params['schoolId']);
$this->db->where('classId =',$params['classId']);
$this->db->where('sectionId =',$params['sectionId']);
//$this->db->where('studentAbsentDate =',$params['absentDate']);
return $this->db->get('student_absent_list')->result();
}
My Expected Results
{
"status": "Success",
"data": [
{
"studentAbsentId": "2"
"studentAbsentDate": "2017-04-11",
"schoolId": "2",
"response":"absent"
},
{
"studentAbsentId": "2"
"studentAbsentDate": "2017-04-13",
"schoolId": "2",
"response":"absent"
}
]
}
Updated answer
{
"status": "Success",
"data": [
{
"absendId": "1",
"studentAbsentId": [
"1",
"2"
],
"studentAbsentDate": "2017-04-11",
"schoolId": "2",
"classId": "1",
"sectionId": "1",
"reg_date": "2017-04-13 01:01:03",
"created_by": "kanniyappan#g2evolution.co.in",
"status": "0"
},
{
"absendId": "2",
"studentAbsentId": [
"1"
],
"studentAbsentDate": "2017-04-12",
"schoolId": "2",
"classId": "1",
"sectionId": "1",
"reg_date": "2017-04-13 01:01:14",
"created_by": "kanniyappan#g2evolution.co.in",
"status": "0"
}
]
}
Try rewriting your model as below:
public function admin_options_listdisplayparent($params)
{
$condition = array(
'status !=' => '1',
'schoolId' => $params['schoolId'],
'classId' => $params['classId'],
'sectionId' => $params['sectionId']
);
$this->db->select('*');
$this->db->where($condition);
$this->db->like('studentAbsentId', '"' . $params['loginId'] . '"', 'both');
return $this->db->get('student_absent_list')->result();
}
Rewrite Controller as below:
public function getAbsentListStaff() {
date_default_timezone_set('Asia/Kolkata');
$loginType = $_POST['loginType'];
if($loginType == 1)
{
$data = array(
"schoolId" => $_POST['schoolName'],
"classId" => $_POST['className'],
"sectionId" => $_POST['sectionName'],
"loginId" =>$_POST['loginId'],
);
$absentresponse_data= $this->Android_login_model->admin_options_listdisplayparent($data);
$absentresponse = array();
foreach ($absentresponse_data as $res)
{
$row = array();
$row['studentAbsentId'] = $_POST['loginId'];
$row['studentAbsentDate'] = $res->studentAbsentDate;
$row['schoolId'] = $res->schoolId;
$row['response'] = 'absent';
$absentresponse[] = $row;
}
if(count($absentresponse) > 0){
$return = array('status'=>"Success",'data'=>$absentresponse);
echo json_encode($return);
} else {
$return = array('status'=>"Error",'description'=>"Data Not Found");
echo json_encode($return);
}
}
}

mixare json, how to configure?

$query = "SELECT id, latitude, longitude, elevation, title, distance, has_detail_webpage, webpage, info FROM korban";
$q=mysql_query($query);
//echo $query;
while($e=mysql_fetch_assoc($q))
$output[]=$e;
print(json_encode($output));
From this code, it will generate like this,
[
{"id":"1","latitude":"-77.036519","longitude":"77.036519","elevation":"0","title":"coba","distance":null,"has_detail_webpage":"0","webpage":"0","info":"0"},
{"id":"3","latitude":"12","longitude":"42","elevation":"21","title":"213","distance":"12","has_detail_webpage":"1","webpage":"12","info":"12"},
{"id":"32","latitude":"","longitude":"","elevation":null,"title":null,"distance":null,"has_detail_webpage":"1","webpage":null,"info":null}
]
But I want something like this,
{ "status": "OK", "num_results": 3, "results":
[ { "id": "2833", "lat": "41.359288", "lng": "-73.646850", "elevation": "53", "title": "Target4", "distance": "1.756", "has_detail_page": "1", "webpage": "" },
{ "id": "2821", "lat": "41.359768", "lng": "-73.646870", "elevation": "0", "title": "Target2", "distance": "1.771", "has_detail_page": "0", "webpage": "" },
{ "id": "2829", "lat": "41.359820", "lng": "-73.646870", "elevation": "0", "title": "Target3", "distance": "1.545", "has_detail_page": "1", "webpage": "" }
] }
How can I do it?
Fetch all your results or do it row by row. Choose yourself. En create the json array afterwards. You also might want to look at your use of mysql_* functions. As they are deprecated now. And you should really switch to MySQli/PDO
$result = array();
while($row = mysql_fetch_assoc($q)) {
$result[] = $row;
}
$output = array('status' => 'OK' , 'num_results' => count($result), 'results' => $result);
echo json_encode($output);
To add the structure you wish to have in your json, first you must create that structure from php before encoding it to json.
$objects = array();
while ($r = mysql_fetch_associ($rs) {
$a = new stdClass();
$a->status = $r['status'];
...
$a->results = array('id' => $r['id']....)
$objects[] = $a;
}
echo json_encode($objects);
$query = "SELECT id, latitude, longitude, elevation, title, distance, has_detail_webpage, webpage, info FROM korban";
$q=mysql_query($query);
$output = array();
if($q) {
$output['status'] = 'OK';
}
$output['num_results'] = mysql_num_rows($q);
while($e=mysql_fetch_assoc($q)) {
$output['results'][]= array (
'id' => $e['id'],
'lat' => $e['latitude'],
'lng' => $e['longitude'],
'elevation' => $e['elevation'],
'title' => $e['title'],
'distance' => $e['distance'],
'has_detail_page' => $e['has_detail_webpage'],
'webpage' => $e['webpage'],
);
}
print(json_encode($output));

Categories