I am trying to fetch data from database in code-igniter .Bur this loop return only one loop .
$userchatData = $this->db->get($this->db->dbprefix('usres_chat'))->result_array();
foreach($userchatData as $key => $userdata)
{
$userdatas[]= array(
'chat_id' => $userdata['chat_id'],
'chat_from' => $userdata['chat_from'],
'created_date' => $userdata['created_date']
);
}
$data['ChatdatabyId'] = $userdatas;
$data['responseCode'] = '200';
$data['responseMessage'] = 'User listing successfully';
echo json_encode($data);
You need to define $userdatas=array(); outside the loop. It is inside the loop that's why it overrides the data and returns the last record.
$userchatData = $this->db->get($this->db->dbprefix('usres_chat'))->result_array();
$userdatas = array();
foreach($userchatData as $key => $userdata){
$userdatas[]= array(
'chat_id' => $userdata['chat_id'],
'chat_from' => $userdata['chat_from'],
'created_date' => $userdata['created_date']
);
}
$data['ChatdatabyId'] =$userdatas;
$data['responseCode'] = '200';
$data['responseMessage'] = 'User listing successfully';
echo json_encode($data);
Hope this will help you :
$userchatData = $this->db->get($this->db->dbprefix('usres_chat'))->result_array();
foreach($userchatData as $key => $userdata)
{
$userdatas[$key]['chat_id'] = $userdata['chat_id'];
$userdatas[$key]['chat_from'] = $userdata['chat_from'];
$userdatas[$key]['created_date'] = $userdata['created_date'];
}
/*print_r($userdatas); output here*/
$data['ChatdatabyId'] = $userdatas;
$data['responseCode'] = '200';
$data['responseMessage'] = 'User listing successfully';
}
echo json_encode($data);
Related
i'm working with laravel project, and i have an issue that is update query result return false value if i update with the same data, how to solve this? do i have to validate first before run the query and send a notification that the data is the same?
well this is my codes
public function update(Request $request)
{
$kamar_id = $request->input('kamar_id');
$title = $request->input('title');
$content = $request->input('content');
$keyword = $request->input('keyword');
$description = $request->input('description');
$prolog = $request->input('prolog');
$path = $request->input('path');
$sort = $request->input('sort');
$status = $request->input('status');
$type = $request->input('type');
$user_id = $request->input('user_id');
if (empty($request->input('path'))) {
$path = serialize(array('data/def.png'));
}else{
$path = serialize(explode(',', $request->input('path')));
}
$data = array('title' => $title,
'content' => $content,
'keyword' => $keyword,
'description' => $description,
'prolog' => $prolog,
'path' => $path,
'sort' => $sort,
'status' => $status,
'type' => $type,
'user_id' => $user_id);
// echo($kamar_id);
$update = Kamar::where('kamar_id',$kamar_id)->update($data);
if ($update) {
$response['status'] = 1;
}else{
$response['status'] = 0;
}
return response()->json($response);
}
thanks for helping me
Laravel Eloquent Update method returns true if anything updated in database from your query and return false if nothing is updated in database from your query.
refer:
https://laravel.com/docs/5.8/eloquent#updates
!nullTry
$update = Kamar::where('kamar_id','=',$kamar_id)->first();
if (!null($update))
{
$update->title = $title;
$update->content = $content;
$update->keyword = $keyword;
$update->description = $description;
$update->prolog = $prolog;
$update->path = $path;
$update->sort = $sort;
$update->status = $status;
$update->type = $type;
$update->user_id = $user_id;
$update->save();
$response['status'] = 1;
}
else
{
$response['status'] = 0;
}
Try using this
$kamarObj = new Kamar();
$kamarData = $kamarObj->find($kamar_id);
$result = $kamarData->update($data);
You can force updated_at column to be updated (or you can create this column if you don't have). So the query will be always updated.
I have to combine two array into single inside Json encode. my code is,
// Controller
$email = $this->input->get('email');
$pass = $this->input->get('password');
$enc_pass = 0;
$get_pass = $this->select->selectData($email);
if(!empty($get_pass)) {
foreach($get_pass as $password)
$enc_pass = $password['user_password'];
$dec_pass = $this->encrypt->decode($enc_pass);
if($pass == $dec_pass) {
$details = array('tag' => 'login', 'status' => 'true');
echo json_encode(array_merge($get_pass, $details));
}
else {
$details = array('tag' => 'login', 'status' => 'false', 'error_msg' => 'Incorrect Email or Password');
echo json_encode($details);
}
}
else {
$details = array('tag' => 'login', 'status' => 'false', 'error_msg' => 'Incorrect Email or Password');
echo json_encode($details);
}
// Model
public function selectData($email) {
$query = $this->db->query('SELECT * FROM tbl_user WHERE email = "'.$email.'"');
$count = $query->num_rows();
if($count > 0)
return $result = $query->result_array();
else
return 0;
}
Now the output for the above code is,
{"0":{"user_id":"1","user_name":"Jithin Varghese","user_email":"jithinvarghese111#gmail.com","user_phone":"9947732296","user_status":"1"},"tag":"login","status":"true"}
Required output is,
{"user_id":"1","user_name":"Jithin Varghese","user_email":"jithinvarghese111#gmail.com","user_phone":"9947732296","user_status":"1","tag":"login","status":"true"}
How to get the required output. I have tried a lot. How to implement this.
Thankyou.
I have these following functions.
public function importExcelFile(){
$file = $_FILES['file']['tmp_name'];
$data = extract_excel_data($file);
$i = 0;
foreach($data['values'] as $dataValues) {
$categories = [];
$brands = [];
$models = [];
foreach($dataValues as $value){
if(array_filter($value)) {
/* If a row does not contain brand/category/model for the product then fetch the resp. info. from previous row */
if(empty(trim($value[0]))) {
$categories[] = $prev_cat;
} else {
$categories[] = strtoupper(trim($value[0]));
$prev_cat = strtoupper(trim($value[0]));
}
if(empty(trim($value[1]))) {
$brands[] = $prev_brand;
} else {
$brands[] = strtoupper(trim($value[1]));
$prev_brand = strtoupper(trim($value[1]));
}
if(empty(trim($value[2]))) {
$models[] = $prev_model;
} else {
$models[] = $value[2];
$prev_model = $value[2];
}
}
}
//insert device category
$this->insert_setups('category', $categories);
//insert brand
$this->insert_setups('brand', $brands);
// Check if branch already exists in the database
$check_branch = $this->global_model->getDetailByWhere('branch', array('name'=>$data['branch'][$i].' branch'))->result();
$branch_arr = [];
//insert branch
if(empty($check_branch)) {
$branch_arr = array(
'name' => $data['branch'][$i].' branch',
'location' => $data['branch'][$i],
'status' => 1,
'created_by' => $this->session->userdata('id'),
'created_on' => date('Y-m-d')
);
$this->global_model->insertData('branch', $branch_arr);
}
$branch_id = $this->global_model->getDetailByWhere('branch', array('name'=>$data['branch'][$i].' branch'))->row()->id;
$db_device_categories = [];
$db_brands = [];
// get categoris, brands
$db_device_categories = $this->arrangeArray('category', $where =array());
$db_brands = $this->arrangeArray('brand', $where =array());
//detail_print($db_brands);
// insert new models from database
foreach(array_unique($models) as $model_key=>$model){
$check_model = $this->global_model->getDetailByWhere('model', array('name'=>$model))->result();
$insert = [];
if(empty($check_model)){
$insert = array(
'name' => $model,
'item_type' => 1,
'category_id' => $db_device_categories[$categories[$model_key]],
'brand_id' => $db_brands[$brands[$model_key]],
'created_by' => $this->session->userdata("id"),
'created_on' => date('Y-m-d'),
);
$this->global_model->insertData('model', $insert);
}
}
$db_device_models = [];
// get models from database
$db_device_models = $this->arrangeArray('model', $where = array('item_type'=>1));
$categoriy_id = [];
$brand_id = [];
$model_id = [];
$opening_stock = [];
// arrange the exported array with respective id
foreach($dataValues as $values){
if(array_filter($values)) {
if(empty(trim($values[0]))) {
$category_id = $prev_cat;
} else {
$category_id = strtoupper(trim($values[0]));
$prev_cat = strtoupper(trim($values[0]));
}
if(empty(trim($values[1]))) {
$brand_id = $prev_brand;
} else {
$brand_id = strtoupper(trim($values[1]));
$prev_brand = strtoupper(trim($values[1]));
}
if(empty(trim($values[2]))) {
$model_id = $prev_model;
} else {
$model_id = $values[2];
$prev_model = $values[2];
}
$opening_stock[] = array(
'category_id' => $db_device_categories[$category_id],
'brand_id' => $db_brands[$brand_id],
'model_id' => $db_device_models[$model_id],
'imei' => (string)$values[3],
'cost_price' => isset($values[5]) ? $values[5] : 0,
'selling_price' => isset($values[6]) ? $values[6] : 0
);
}
}
$group_by_model = [];
// group the array by model_id
foreach(array_unique($models) as $model1){
$where = $db_device_models[$model1];
$group_by_model[] = array_filter($opening_stock, function($elements) use ($where){
return $elements["model_id"] == $where;
});
}
if(!$this->purchase_model->insertOpeningStock($group_by_model, $branch_id)){
$this->session->set_flashdata('error', 'Opening stock of devices insertion failed.');
redirect('purchase/uploadExcelFile');
}
$i++;
}
$this->session->set_flashdata('success', 'Opening stock of devices added successfully.');
redirect('purchase/uploadExcelFile');
}
private function arrangeArray($table, $where){
$list = $this->global_model->getDetailByWhere($table, $where)->result_array();
foreach($list as $item){
$name = $item['name'];
$arranged_list[$name] = $item['id'];
}
return !empty($arranged_list) ? $arranged_list : NULL;
}
private function insert_setups($table_name, $setups){
foreach(array_unique($setups) as $value){
$check_setup = $this->global_model->getDetailByWhere($table_name, array('name'=>$value))->result();
if(empty($check_setup)){
$insert = array(
'name' => $value,
'created_by' => $this->session->userdata("id"),
'created_on' => date('Y-m-d'),
);
$this->global_model->insertData($table_name, $insert);
}
}
}
What this function does is, it extracts data from the uploaded excel file and inserts the data to various tables accordingly. Now as you can see, there are multiple queries running in different locations inside the importExcelFile() method. So my question is, how do I use codeigniter transaction in such a way that all the queries inside this function are performed atomically. If any one query fails, all other query's work is rolled back. Also, is this code considered clean ?
P.S. I'm so sorry if my last question was inappropriate here.
this might be helpful to you.
transactions in codeigniter
$this->db->trans_begin();
$this->db->query('AN SQL QUERY...');
$this->db->query('ANOTHER QUERY...');
$this->db->query('AND YET ANOTHER QUERY...');
if ($this->db->trans_status() === FALSE)
{
$this->db->trans_rollback();
}
else
{
$this->db->trans_commit();
}
Here is my code:
<?php
while ($row = mysqli_fetch_assoc($searching_user))
{
$salon_name = ucfirst($row['service_name']);
$salon_id = ucfirst($row['id']);
$salon_address = ucwords($row['address']);
$salon_area = ucwords($row['area']);
$salon_city = ucwords($row['city']);
$salon_specialty = ucwords($row['specialty']);
$img = $row['image_url'];
$response["error"] = FALSE;
$response["service_name"] = $salon_name;
echo json_encode($response);
}
?>
after this I'm getting the response in this format
{"error":false,"service_name":"Mike
salon"}{"error":false,"service_name":"Michel salon"}
{"error":false,"service_name":"Michel salon"}{"error":false,"service_name":"Mike Salon"}
{"error":false,"service_name":"Etta Salon"}
I simply want this response like this
[ {"error":false,"service_name":"Mike
salon"},{"error":false,"service_name":"Michel
salon"},{"error":false,"service_name":"Michel
salon"},{"error":false,"service_name":"Mike Salon"},
{"error":false,"service_name":"Etta Salon"}]
Kindly help me to get a proper response form for json .
Thanks
Don't json_encode() the single results, but put them into an array and finally json_encode() that:
<?php
$response = [];
while ($row=mysqli_fetch_assoc($searching_user)) {
$salon_name = ucfirst($row['service_name']);
$salon_id = ucfirst($row['id']);
$salon_address = ucwords($row['address']);
$salon_area = ucwords($row['area']);
$salon_city = ucwords($row['city']);
$salon_specialty = ucwords($row['specialty']);
$img = $row['image_url'];
$response[] = [
'error' => FALSE,
'service_name' => $salon_name,
// you may want to add more attributes here...
];
}
echo json_encode($response);
I personally suggest to shorten this:
<?php
$response = [];
while ($row=mysqli_fetch_assoc($searching_user)) {
$response[] = [
'error' => FALSE,
'service_name' => ucfirst($row['service_name']),
'salon_id' => $row['id'],
'salon_address' => ucwords($row['address']),
'salon_area' => ucwords($row['area']),
'salon_city' => ucwords($row['city']),
'salon_specialty' => ucwords($row['specialty']),
'img' => $row['image_url'],
];
}
echo json_encode($response);
You are trying to encode single results, Try to create a array will all the results and encode it out side the loop.
while ($row=mysqli_fetch_assoc($searching_user)) {
$salon_name = ucfirst($row['service_name']);
$salon_id = ucfirst($row['id']);
$salon_address = ucwords($row['address']);
$salon_area = ucwords($row['area']);
$salon_city = ucwords($row['city']);
$salon_specialty = ucwords($row['specialty']);
$img = $row['image_url'];
$response["error"] = FALSE;
$response["service_name"]=$salon_name;
// Added this line
$responses[] = $response;
}
//Encode all results
echo json_encode($responses );
Am trying to encode an array to json for use with jquery.
This is the function from my model
function get_latest_pheeds() {
$this->load->helper('date');
$time = time();
$q = $this->db->select("user_id,pheed_id,pheed,datetime,COUNT(pheed_comments.comment_id) as comments")
->from('pheeds')
->join('pheed_comments','pheed_comments.P_id=pheeds.pheed_id','left')
->group_by('pheed_id')
->order_by('datetime','desc')
->limit(30);
$rows = $q->get();
foreach($rows->result_array() as $row) {
$data['user_id'] = $row['user_id'];
$data['pheed_id'] = $row['pheed_id'];
$data['pheed'] = $row['pheed'];
$data['comments'] = $row['comments'];
$data['datetime'] = timespan($row['datetime'],$time);
}
return $data;
}
And this is from my controller
function latest_pheeds() {
if($this->isLogged() == true) {
$this->load->model('pheed_model');
$data = $this->pheed_model->get_latest_pheeds();
echo json_encode($data);
return false;
}
}
It returns only 1 row from the database when I run the code in the browser.
Please help me out
You are overwriting data in every iteration !!
Use something like
$data[] = array(
'user_id' => $row['user_id'];
'pheed_id' => $row['pheed_id'];
'pheed' => $row['pheed'];
'comments' => $row['comments'];
'datetime' => timespan($row['datetime'],$time);
) ;
This is good but your syntax should be 'user_id' => $row['user_id'], for each element of the array