get data from array in cakephp - php

I'm trying to get the data from array in my controller php on Cakephp.
I have this function:
public function updateUserStatus() {
if(isset($this->params['url']["pcs"])) {
$uus = array( "pcs" =>$this->params['url']["pcs"] );
$trans = $this->Transaction->updateUserStatus($uus);
} else {
$trans = "failed";
}
$this->set('trans', $trans);
$this->layout = 'ajax';
}
And I want to get the data from status_id who have this response:
Array (
[0] => Array
(
[status_id] => 2
)
[1] => Array
(
[rem_time] => 66
)
)
How can I do it?
My question is how can i get the data for status_id ?

public function updateUserStatus() {
if (isset($this->params['url']["pcs"])) {
$uus = array("pcs" =>$this->params['url']["pcs"]);
$trans = $this->Transaction->updateUserStatus($uus);
} else {
$trans = "failed";
}
$currentStatus = 0;
if (is_array($trans) && isset($trans['status_id'])) {
$currentStatus = $trans['status_id'];
}
$this->set('trans', $trans);
$this->layout = 'ajax';
}
public function updateUserStatus($uus){
if(isset($uus["pcs"])) {
$sql = "SELECT status_id as status_id , rem_time as rem_time FROM phones WHERE pcs = '".$uus["pcs"]."' LIMIT 1";
$query = $this->query($sql);
return $query[0]['phones'];
} else {
return "failed";
}
}
Notice, we are returning $query[0]['phones'].
Let me know if it works.
The code could also use some refactoring.
For example, why is the function called updateUserStatus if it is only returning the result of a query? It should also always return an array, for consistency.

Related

how to break function array in rows?

I have this php function in codeigniter where it fetches the data from my database:
function fetch_data()
{
$data = $this->projectionchart_model->make_query();
$array = array();
foreach($data as $row)
{
$array[] = $row;
}
$output = array(
'current' => intval($_POST["current"]),
'rowCount' => 10,
'total' => intval($this->projectionchart_model->count_all_data()),
'rows' => $array
);
echo json_encode($output);
}
I want to use the number_format function to some of columns and right now it's building everything in an array. How could I remove the array and list the data individually as variables so I can apply a function to some of them and then output them?
Thank you
Edit: explaining in more detail
This function fetch_data() calls the make_query() function stored in the projectionchart_model file which contains the following:
function make_query()
{
if(isset($_POST["rowCount"]))
{
$this->records_per_page = $_POST["rowCount"];
}
else
{
$this->records_per_page = 10;
}
if(isset($_POST["current"]))
{
$this->current_page_number = $_POST["current"];
}
$this->start_from = ($this->current_page_number - 1) * $this->records_per_page;
$this->db->select("*");
$this->db->from("projection_chart");
if(!empty($_POST["searchPhrase"]))
{
$this->db->like('ae', $_POST["searchPhrase"]);
$this->db->or_like('client', $_POST["searchPhrase"]);
$this->db->or_like('product', $_POST["searchPhrase"]);
$this->db->or_like('week_of', $_POST["searchPhrase"]);
$this->db->or_like('month', $_POST["searchPhrase"]);
$this->db->or_like('type', $_POST["searchPhrase"]);
}
if(isset($_POST["sort"]) && is_array($_POST["sort"]))
{
foreach($_POST["sort"] as $key => $value)
{
$this->db->order_by($key, $value);
}
}
else
{
$this->db->order_by('id', 'DESC');
}
if($this->records_per_page != -1)
{
$this->db->limit($this->records_per_page, $this->start_from);
}
$query = $this->db->get();
return $query->result_array();
}
So the output currently is this:
I want to format the Planned Spend, Cleared and Total Commission with the number_format php function but right now it's all in an array.
How could I accomplish this?

Updating multiple records in database using Codeigniter

Am trying to update multiple records in the database but my case I have a column total, which I want to update to different values. I haven't tried much here but hope I could get a clue on how to go about this.
My controller
public function update_record()
{
$id = ["19821", "19923", "19966", "19967"];
$total = ["8", "118", "90", "100"];
if ($this->some_model->batch_data('records', $total, $id) == true) {
echo "yes";
} else {
echo "no";
}
}
The Model
public function batch_data($table, $data, $where)
{
$this->db->where_in('id',$where);
$this->db->set('total',$data);
$this->db->update($table);
return true;
}
I have not tested this yet but currently looking for a more and efficient way of doing this.
If you still want to update multiple records using the update_batch method, you could first assign the id and total as key-value arrays, then use the update_batch method.
Controller :
public function update_record()
{
$id = ["19821", "19923", "19966", "19967"];
$total = ["8", "118", "90", "100"];
$update_data = [];
foreach ($id as $key => $value) {
$update_data[] = [
'id' => $value,
'total' => $total[$key]
];
}
if ($this->some_model->batch_data('records', $update_data) == true) {
echo "yes";
} else {
echo "no";
}
}
Model :
public function batch_data($table, $data)
{
$this->db->update_batch($table, $data, 'id'); // this will set the id column as the condition field
return true;
}
Output :
// preview query output :
// UPDATE `records`
// SET
// `total` =
// CASE
// WHEN `id` = '19821' THEN 8
// WHEN `id` = '19923' THEN 118
// WHEN `id` = '19966' THEN 90
// WHEN `id` = '19967' THEN 100
// ELSE `total`
// END
// WHERE `id` IN ('19821', '19923', '19966', '19967')
As per my comment. This is a method that combines the array in to key/value pairs and updates them 1x1 wrapped in a transaction (so if one query fails nothing changes).
This is the method I would personally use as I don't like update_batchs internal workings (cases).
$id = ["19821", "19923", "19966", "19967"];
$total = ["8", "118", "90", "100"];
$combined = array_combine($id, $total);
if (count($combined) > 0) {
$this->db->trans_start();
foreach ($combined as $id => $total) {
$this->db->set('total', $total);
$this->db->where('id', $id);
$this->db->update('sometable');
}
$this->db->trans_complete();
return $this->db->trans_status();
}
return true;
Try this, Only for single where condition
Controller:
public function update_record()
{
$tableName = "records";
$id = ["19821", "19923", "19966", "19967"];
$total = ["8", "118", "90", "100"];
$update_data = [];
foreach ($id as $key => $value) {
$update_data[] = [
'id' => $value,
'total' => $total[$key]
];
}
$whereKey = 'id';
$this->$this->some_model->batch_data($tableName, $updateData, $whereKey);
}
Model:
public function batch_data($tableName, $updateData, $whereKey)
{
$this->db->update_batch($tableName, $updateData, $whereKey);
}

How to fetch and return record with total number of records in codeigniter

I am working with rest api using codeigniter,I want to fetch records + total records + per page records,but not worked for me
Here is my function in controller
<?php
public function search_shop()
{
$users['rec'] = $this->Model_users->find_shop($_POST);
if($users['rec']!="")
{
$responseJSON = array("Status" => true,"Result" => $users['rec']);
header("content-type:application/json");
$response = json_encode($responseJSON);
echo $response;
}
else
{
$responseJSON = array("Status" => false,"Message" => "There is no matching record");
header("content-type:application/json");
$response = json_encode($responseJSON);
echo $response;
}
}
And here is my "find_shop" function in model,How can i fetch all records with total number of records and per page records ?
public function find_shop()
{
$add_data['page_number'] = ($this->input->post('page_number') && !empty($this->input->post('page_number'))) ? $this->input->post('page_number') : NULL;
$add_data['search'] = ($this->input->post('search') && !empty($this->input->post('search'))) ? $this->input->post('search') : NULL;
$records="10";
$mins="10";
if($add_data['page_number']=="" || $add_data['page_number']=="0" || $add_data['page_number']=="1")
{
$starting_row="0";
$last_row="10";
}
else
{
$last_row="9";
$cd="1";
$lim="10";
$starting_row=$add_data['page_number']*$lim-$last_row-$cd;
$last_row=$add_data['page_number']*$records-$cd;
}
$this->db->select('*');
$this->db->from('shop s');
$this->db->like('shop_name',$add_data['search']);
$this->db->or_like('city',$add_data['search']);
$this->db->limit($last_row,$starting_row);
$query = $this->db->get();
if ( $query->num_rows() > 0 )
{
$row = $query->result_array();
return $row;
return $query->num_rows;
}
else
{
return false;
}
}
?>
Try This, Hope it helps
in the Controller please test this after model related changes
$users = array();
$users = $this->Model_users->find_shop($_POST);
echo'<pre>';print_r($users);die;
in the Model, There is a mistake in the return, You cannot do two return at the same time
$query = $this->db->get();
if ( $query->num_rows() > 0 )
{
$data = array();
$data['row'] = $query->result_array();
$data['total_records'] = $this->db->count_all_results('shop');
$data['per_page_records'] = $query->num_rows();
return $data;
}else{
return array('row'=>array(),'total_records'=>'0','per_page_records'=>'0');
}
Change your if condition like this:
$records="10"; // This is records per page showing
if ($add_data['page_number']=="" || $add_data['page_number']=="0" || $add_data['page_number']=="1")
{
$starting_row="0";
} else {
$starting_row = ($add_data['page_number'] - 1) * $records;
}
You need to set limit and offset of query. For example: limit 0, 10: this will show first 10 records. Here 0 is starting point and 10 is the length of records which you want to show. 10 will always be same as you are showing 10 records. Limit 10, 10: it will show records from 10 to 19. hope it clears your doubt.

how to implode and insert values into db in codeigniter?

How to implode and insert values into the database in CodeIgniter?
I am creating multiple choice quiz script using CodeIgniter framework. I want to store user results like this:
id userid q_id answer_id time_taken
1 1 1,2,3,4,5 2,3,4,5,3 4,5,7,6,7
in my controller:
public function insert_result()
{
$this->load->model('quiz_models');
$user_id=$this->input->post('user_id');
$qq_id=$this->input->post('questionid');
$answer_id=$this->input->post('AnswerID');
$time_taken=$this->input->post('timetaken');
$question_no=$this->input->post('question_no');
$bd = "$question_no";
switch ($bd) {
case"1":
$data=array('user_id'=>$user_id,
'q_id'=>$qq_id,
'answer_id'=>$answer_id,
'time_taken'=>$time_taken);
$this->quiz_models->insert_result($data);
break;
case"2":
quiz_test();
break;
case"3":
quiz_test();
break;
case"4":
quiz_test();
break;
case"5":
quiz_test();
$this->session->unset_userdata('lastids');
break;
default:
echo "something is wrong";
}
}
public function quiz_test()
{
$this->load->model('quiz_models');
$quiz=$this->quiz_models->quiz_test();
foreach($quiz as $row){
$qid=$row->q_id;
$ans=$row->answer_id;
$time=$row->time_taken;
$a = array("$qq_id","$qid");
$b = array("$answer_id","$ans");
$c = array("$time_taken","$time");
$comma = implode(",",$a);
$comma1 = implode(",",$b);
$comma2 = implode(",",$c);
$data=array('q_id'=>$comma,
'answer_id'=>$comma1,
'time_taken'=>$comma2);
$this->quiz_model->update_result($data);
}
}
}
and Model:
function insert_result($data)
{
$this->dbb->insert('results',$data);
$sectio=$this->db->insert_id();
$this->session->set_userdata('lastids',$sectio);
}
function quiz_test()
{
$ses_id = $this->session->userdata('lastids');
$sql = "SELECT q_id, answer_id, time_taken FROM results WHERE id='$ses_id'";
$query = $this->dbb->query($sql);
$result = $query->result();
return $result;
}
function update_result($data){
$ses_id = $this->session->userdata('lastids');
$this->db->where('id',$ses_id);
$this->db->update('results',$data);
}
when i run it nothing happened,not showing any error where do i mistake?
pls help me what am i doing wrong
First of all - i think you've a major problem in your DB structure
Normalize your Data
You should prevent to store your information in the table like that.
It should be possible to normalize your data properly. If you dont know
how to do that the following link could be interesting:
Normalization in MYSQL
However a possible solution would be to structure your data:
In order to do that - create a save Method in your Model to split between update and insert - this model could look like
class Quiz_Models
{
private $arrPostData;
public function save($arrPostData = false)
{
$this->arrPostData = (!$arrPostData) ? $this->input->post() : $arrPostData;
$id = $this->session->userdata("lastids");
if ($id)
{
$query = $this->db
->select("*")
->from("results")
->where("id",$id)
->get();
if ($query->num_rows() == 1)
{
$this->update($query->row(0));
}
else return false;
}
else
{
$this->insert();
}
if ($this->arrPostData['question_no'] == 10) $this->session->unset_userdata("lastids");
}
private function update($objData)
{
$objCollection = new Quiz_Collection();
$objCollection->userId = $objData->userid;
$objCollection->id = $objData->id;
$arrData = explode($objData->q_id);
foreach($arrData AS $key => $quizId)
{
$objQuiz = new stdClass();
$objQuiz->q_id = $quizId;
$objQuiz->answer_id = explode($objData->answer_id)[$key];
$objQuiz->time_taken = explode($objData->answer_id)[$key];
$objCollection->append($objQuiz);
}
$objQuizFromPost = new stdClass();
$objQuizFromPost->q_id = $this->arrPostData["questionid"];
$objQuizFromPost->answer_id = $this->arrPostData['AnswerID'];
$objQuizFromPost->time_taken = $this->arrPostData['timetaken'];
$objCollection->addQuizFromPost($objQuizFromPost);
$this->db
->where("id",$objCollection->id)
->update("results",$objCollection->getDbData());
}
private function insert()
{
$objCollection = new Quiz_Collection();
$objCollection->userId = $this->arrPostData['user_id'];
$objQuizFromPost = new stdClass();
$objQuizFromPost->q_id = $this->arrPostData["questionid"];
$objQuizFromPost->answer_id = $this->arrPostData['AnswerID'];
$objQuizFromPost->time_taken = $this->arrPostData['timetaken'];
$objCollection->addQuizFromPost($objQuizFromPost);
$this->db->insert("results",$objCollection->getDbData());
$this->session->set_userdata("lastids", $this->db->insert_id());
}
}
as an addition you need a Collection Object (put this below your model)
class Quiz_Collection extends Array_Object
{
public $userId = 0;
public $id = 0;
public function addQuizFromPost($objQuiz)
{
if (intval($objQuiz->q_id) > 0)
{
foreach($this AS $key => $obj)
{
if ($obj->q_id == $objQuiz->q_id)
{
$this->offsetSet($key, $objQuiz);
return true;
}
}
$this->append($objQuiz);
return true;
}
return false;
}
public function sortQuizData($objA, $objB)
{
if ($objA->q_id == $objB->q_id) return 0;
return ($objA->q_id < $objB->q_id) ? -1 : 1;
}
public function getDbData()
{
$this->uasort(array($this,"sortQuizData"));
$arrData = $this->getArrayCopy();
$arrDbData = [
"userid" => $this->userId,
"q_id" => implode(array_map(function($obj){ return $obj->q_id;},$arrData),","),
"answer_id" => implode(array_map(function($obj){ return $obj->answer_id;},$arrData),","),
"time_taken" => implode(array_map(function($obj){ return $obj->time_taken;},$arrData),","),
];
return $arrDbData;
}
}
pS: this is just an instruction how you can do that in a proper way. Pls study this code. If you still don't understand whats going on, feel free to ask.

insert array element into database

I have this function : it's work correctly,
function ms_get_did_detail($id) {
global $link;
$q2="select Dest,Priority from destpr where Id='$id'";
if($res2=mssql_query($q2)) {
while($row2[]=mssql_fetch_array($res2,MSSQL_ASSOC)) {
return $row2;
}
return 0;
}
return 0;
}
I want insert every element (every Dest & Priority) into MYSQL
if($info=ms_get_did_detail($value)) {
print_r($info);
$destination = $info['Dest'];
$priority = $info['Priority'];
my_did_destination ($priority , $dest , $active , $did_voip , $cc_id);
}
It returns array like this :
[0]=> Array (
[Dest] => 100
[Priority] => 1
)
[1]=> Array (
[Dest] => 200
[Priority] => 3
)
[2] => (
)
also , I have this function to insert value in database :
function my_did_destination($priority="",$destination="") {
global $link_voip;
$sql="INSERT INTO cc_did_destination (destination,priority)
VALUES ('$destination','$priority')";
$retval = mysql_query( $sql , $link_voip);
if(! $retval ) {
die('Could not enter data: ' . mysql_error());
}
}
but It's insert empty value within
You are inserting all rows with an ID of 0, so, if a row with id=0 already exists, it will fail and will not be inserted.
Maybe the easiest solution would be to make yout ID column autoincrement with an SQL statement like:
ALTER TABLE cc_did_destination
MODIFY COLUMN id INT auto_increment;
And then change your INSERT statement for:
$sql="INSERT INTO cc_did_destination (destination,priority)
VALUES ('$destination','$priority')";
Your $info is array of rows, it has numeric keys, not 'Dest'.
You should add index, like $dest = $info[0]['Dest'].
if($info=ms_get_did_detail($value))
{
print_r($info);
$dest = $info[0]['Dest'];
$priority = $info[0]['Priority'];
my_did_destination ($priority , $dest , $active , $did_voip , $cc_id);
}
Or you can iterate through $info with a loop:
if($info=ms_get_did_detail($value))
{
foreach($info as $row) {
$dest = $row['Dest'];
$priority = $row['Priority'];
my_did_destination ($priority , $dest);
}
}
also, remove id from your insert statement
your array is:
[0]=> Array (
[Dest] => 100
[Priority] => 1
)
[1]=> Array (
[Dest] => 200
[Priority] => 3
)
[2] => (
)
so it is a multidimensional array. if you need to insert all those entries, you shouldn't run multiple queries for the same thing. just use mysql batch insert syntax. (e.g. INSERT INTO tbl (col1,col2,col3) VALUES(a,b,c),(d,e,f),(g,h,i))
build the query string for insert.
foreach($a as $i => $v)
{
$b[] = '("'.$v['Dest'].'","'.$v['Priority'].'")';
}
$c = implode(',', $b);
$sql = "INSERT INTO cc_did_destination (destination,priority)
VALUES ".$c;
then run the query
N.B.
Please, don't use mysql_* functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.
There are a couple of issues here.
Firstly your first function returns an array of arrays. Ie, it returns an array with subscript 0 for the first row (it only ever returns one rows details), which is an array containing that rows details.
You assign this to the $info variable, so it contains:-
[0]=> Array (
[Dest] => 100
[Priority] => 1
)
You then assign $info['Dest'] to $destination and $info['Priority'] to $priority. However neither of these exist. You would need $info[0]['Dest'] and $info[0]['Priority'].
2nd issue is that you are trying to assign a specific value to the auto increment id field. Just leave it out of the insert, or give it a value of null.
Quick rewrite and I would suggest you need something like this:-
<?php
if($info=ms_get_did_detail($value))
{
print_r($info);
foreach($info AS $info_row)
{
$destination = $info_row['Dest'];
$priority = $info_row['Priority'];
my_did_destination ($priority , $dest , $active , $did_voip , $cc_id);
}
}
function ms_get_did_detail($id)
{
global $link;
$q2="select Dest,Priority from destpr where Id='$id'";
if($res2=mssql_query($q2))
{
if ($row2[]=mssql_fetch_array($res2,MSSQL_ASSOC))
{
while ($row2[]=mssql_fetch_array($res2,MSSQL_ASSOC))
{
}
return $row2;
}
else
{
return 0;
}
}
return 0;
}
function my_did_destination($priority="",$destination="")
{
global $link_voip;
$priority = mysql_real_escape_string($priority);
$destination = mysql_real_escape_string($destination);
$sql="INSERT INTO cc_did_destination (id,destination,priority) VALUES (NULL,'$destination','$priority')";
$retval = mysql_query( $sql , $link_voip);
if(! $retval )
{
die('Could not enter data: ' . mysql_error());
}
}
EDIT
If you want to avoid multiple inserts unnecessarily then it might be easier to use an object. This way you can do the inserts easily when there are enough batched up (I normally do 255 at a time).
Something like this, although you probably should use mysqli_*
<?php
if($info=ms_get_did_detail($value))
{
print_r($info);
$insert_object = new insert_details($link_voip);
foreach($info AS $info_row)
{
$insert_object->set_row($info_row['Priority'], $info_row['Dest']);
}
unset($insert_object);
}
function ms_get_did_detail($id)
{
global $link;
$q2="select Dest,Priority from destpr where Id='$id'";
if($res2=mssql_query($q2))
{
if ($row2[]=mssql_fetch_array($res2,MSSQL_ASSOC))
{
while ($row2[]=mssql_fetch_array($res2,MSSQL_ASSOC))
{
}
return $row2;
}
else
{
return 0;
}
}
return 0;
}
class insert_details()
{
private $db;
private $insert_row = array();
public function __CONSTRUCT($db)
{
$this->db = $db;
}
public function __DESTRUCT()
{
$this->do_insert();
}
public function set_row($priority="",$destination="")
{
$priority = mysql_real_escape_string($priority, $this->db);
$destination = mysql_real_escape_string($destination, $this->db);
$this->insert_row[] = "(NULL,'$destination','$priority')";
if (count($this->insert_row) > 255)
{
$this->do_insert();
}
}
private function do_insert()
{
$sql="INSERT INTO cc_did_destination (id,destination,priority) VALUES ".implode(',', $this->insert_row);
$retval = mysql_query($sql, $this->db);
if(! $retval )
{
die('Could not enter data: ' . mysql_error());
}
$this->insert_row = array();
}
}
Quick rough mysqli_* equivalent, assuming that $link_voip is a mysqli connection. Note that prepared statements with bound parameters are an option (and it makes it harder to forget to escape variables), but it can become a bit messy when you are doing multiple inserts like this.
<?php
if($info=ms_get_did_detail($value))
{
print_r($info);
$insert_object = new insert_details($link_voip);
foreach($info AS $info_row)
{
$insert_object->set_row($info_row['Priority'], $info_row['Dest']);
}
unset($insert_object);
}
function ms_get_did_detail($id)
{
global $link;
$q2="select Dest,Priority from destpr where Id='$id'";
if($res2=mssql_query($q2))
{
if ($row2[]=mssql_fetch_array($res2, MSSQL_ASSOC))
{
while ($row2[]=mssql_fetch_array($res2, MSSQL_ASSOC))
{
}
return $row2;
}
else
{
return 0;
}
}
return 0;
}
class insert_details()
{
private $db;
private $insert_row = array();
public function __CONSTRUCT($db)
{
$this->db = $db;
}
public function __DESTRUCT()
{
$this->do_insert();
}
public function set_row($priority="",$destination="")
{
$priority = mysqli_real_escape_string($this->db, $priority);
$destination = mysqli_real_escape_string($this->db, $destination);
$this->insert_row[] = "(NULL,'$destination','$priority')";
if (count($this->insert_row) > 255)
{
$this->do_insert();
}
}
private function do_insert()
{
$sql="INSERT INTO cc_did_destination (id,destination,priority) VALUES ".implode(',', $this->insert_row);
$retval = mysqli_query($this->db, $sql);
if(! $retval )
{
die('Could not enter data: ' . mysqli_sqlstate($this->db));
}
$this->insert_row = array();
}
}

Categories