How to insert multidimentional array to mysql in codeigniter - php

i have a mysql table with field id,meta_key,meta_value. i want to add multiple metavalue and metakeys when i add any listing, here is my controller code
$listingid=145;
$metakey=array();
$metavalue=array();
if($data['submitlisting'])
{
if($vehicle_make != "")
{
$metakey[]="vehicle_make";
$metavalue[]=$vehicle_make;
}
if($vehicle_mileage != "")
{
$metakey[]="vehicle_mileage";
$metavalue[]=$vehicle_mileage;
}
if($vehicle_year != "")
{
$metakey[]="vehicle_year";
$metavalue[]=$vehicle_year;
}
$data['listingmeta']=$this->Classifieds_model->addmeta($listingid,$metakey,$metavalue,$data);
here is the model code
function addmeta($listingid,$metakey,$metavalue,$data2)
{
$this->load->database();
$data = array(
'classifieds_id' => $listingid ,
'meta_key' => 'location' ,
'meta_value' => 'mangalore'
);
foreach($data2['listingmeta'] as $meta)
$this->db->insert('classifieds_meta',
array(
'classifieds_id' => $listingid ,
'meta_key' => 'location' ,
'meta_value' => 'mangalore'
)
);
}
but the above code doesnt work, please can someone help?

The propest way, it's better to avoid SQL commands in loops :
$insert_batch = array();
for($i=0; $i<count($); $i++)
{
$insert['classifieds_id'] = $listingid;
$insert['meta_key'] = $metakey[$i];
$insert['meta_value'] = $metavalue[$i];
$insert_batch []= $insert;
}
$this->db->insert_batch('classifieds_meta', $insert_batch);

1) Create a simple model function just to insert data array. (always try to frame your model functions such that they can be re-used)
function addmeta($data)
(
$this->db->insert('classifieds_meta', $data);
)
2) Now send the required array to the model through the Controller below
array(
'classifieds_id' => $listingid ,
'meta_key' => 'location' ,
'meta_value' => 'mangalore'
)
$listingid=145;
$metakey=array();
$metavalue=array();
if($data['submitlisting'])
{
if($vehicle_make != "")
{
$metakey[]="vehicle_make";
$metavalue[]=$vehicle_make;
}
if($vehicle_mileage != "")
{
$metakey[]="vehicle_mileage";
$metavalue[]=$vehicle_mileage;
}
if($vehicle_year != "")
{
$metakey[]="vehicle_year";
$metavalue[]=$vehicle_year;
}
$insert = array();
for($i=0; $i<count($metakey); $i++)
{
$insert['classifieds_id'] = $listingid;
$insert['meta_key'] = $metakey[$i];
$insert['meta_value'] = $metavalue[$i];
$this->Classifieds_model->addmeta($insert);
}
}

can try this code into controller:
$ex=count($this->input->post('ex'));
$count =count($this->input->post('ex'));
$data2 =array();
for($i=0; $i<$count; $i++)
{
$data2[] = array(
'ex' => $ex[$i],
);
}
$this->db->insert_batch('table', $data2);

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?

Check if array exist by two keys with PHP

I'd like to check if array exist by two keys: id and type
This code just check by id:
if (isset($_POST['type'])) {
$type = $_POST['type'];
}
else {
$type = '';
}
if (array_key_exists($id, $_SESSION['cart'])) {
$_SESSION['cart'][$id]['quantity'] += $quantity;
} else {
$_SESSION['cart'][$id] = $line;
}
I have tried with this code but it doesn't work:
if (array_key_exists($id, $_SESSION['cart']) && array_key_exists($type, $_SESSION['cart'])) {
$_SESSION['cart'][$id]['quantity'] += $quantity;
} else {
$_SESSION['cart'][$id] = $line;
}
$_SESSION['cart'] is an array contains arrays of $line
$line = array(
'id' => $id,
'type' => $type,
'quantity' => $quantity,
'price' => $price,
'picture' => $dish->getPicture()->getWebPath(),
);
This is the output of $_SESSION['cart']:
As you see in th last array with id 55 and type "french bred" , what I'd like to do is to check if th user chose the same product but a with different type so insert new line else if the same product and the same type so just update quantity.
Something like this should do, however the question is too vague and too little code is shown for me to properly understand your problem
$lineExists = false;
foreach($_SESSION['cart'] as $index => $line){
if($line['id'] === $id)
{
$_SESSION['cart'][$index]['quantity'] += $quantity;
$lineExists = true;
}
}
if(!$lineExists)
{
$_SESSION['cart'][] = $newLine;
}
If you want to check if type and id exists then you should do something like this
if (array_key_exists('id', $_SESSION['cart']) && array_key_exists('type', $_SESSION['cart'])) {
// stuff here..
}
if $id is the value of the key id so 'id' => 5 then you should check like this:
if ($_SESSION['cart']['type'] == $id) {
// stuff here
}
Hope this somewhat helps you further!

How to filter based on I18n content with pagination component?

I have comeup with strange problem in cakephp 3.4. I am running filter query on i18n content like this.
if($this->request->query("q")){
$this->paginate["conditions"][$this->ContractTypes->translationField('title').' LIKE'] = '%'.$this->request->query("q").'%';
}
but following call is ending up in Database error
$records = $this->paginate($this->ContractTypes);
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'ContractTypes_title_translation.content' in 'where clause' SELECT (COUNT(*)) AS `count` FROM contract_types ContractTypes WHERE ContractTypes_title_translation.content like :c0
The paginator's count query is not joing i18n table. What is the best approach to solve this problem.
Thanks in advance,
I have solved this by creating my custom paginator component by editing the paginate function. My paginator contains following code incase somebody else is facing the same problem.
namespace Console\Controller\Component;
use Cake\Controller\Component\PaginatorComponent as BasePaginator;
class PaginatorComponent extends BasePaginator
{
public function paginate($object, array $settings = [])
{
$query = null;
if ($object instanceof QueryInterface) {
$query = $object;
$object = $query->repository();
}
$alias = $object->alias();
$options = $this->mergeOptions($alias, $settings);
$options = $this->validateSort($object, $options);
$options = $this->checkLimit($options);
$options += ['page' => 1, 'scope' => null];
$options['page'] = (int)$options['page'] < 1 ? 1 : (int)$options['page'];
list($finder, $options) = $this->_extractFinder($options);
if (empty($query)) {
$query = $object->find($finder, $options);
} else {
$query->applyOptions($options);
}
$cleanQuery = clone $query;
// My Modification Starts Here
$table = $cleanQuery->repository();
$results = $query->all();
$numResults = count($results);
$count = $numResults ? $cleanQuery->select([
"count"=>$cleanQuery
->func()
->count($table->alias().'.'.$table->primaryKey())
])->first()->count : 0;
// My Modification ends Here
$defaults = $this->getDefaults($alias, $settings);
unset($defaults[0]);
$page = $options['page'];
$limit = $options['limit'];
$pageCount = (int)ceil($count / $limit);
$requestedPage = $page;
$page = max(min($page, $pageCount), 1);
$request = $this->_registry->getController()->request;
$order = (array)$options['order'];
$sortDefault = $directionDefault = false;
if (!empty($defaults['order']) && count($defaults['order']) == 1) {
$sortDefault = key($defaults['order']);
$directionDefault = current($defaults['order']);
}
$paging = [
'finder' => $finder,
'page' => $page,
'current' => $numResults,
'count' => $count,
'perPage' => $limit,
'prevPage' => $page > 1,
'nextPage' => $count > ($page * $limit),
'pageCount' => $pageCount,
'sort' => key($order),
'direction' => current($order),
'limit' => $defaults['limit'] != $limit ? $limit : null,
'sortDefault' => $sortDefault,
'directionDefault' => $directionDefault,
'scope' => $options['scope'],
];
if (!$request->getParam('paging')) {
$request->params['paging'] = [];
}
$request->params['paging'] = [$alias => $paging] + (array)$request->getParam('paging');
if ($requestedPage > $page) {
throw new NotFoundException();
}
return $results;
}
}

Cakephp pagination custom order

I need to set the pagination order of my register based on field ($results[$key]['Movimento']['status']) created in afterFind callback.
afterFind:
public function afterFind($results, $primary = false) {
foreach ($results as $key => $val) {
if(isset($val['Movimento']['data_vencimento'])) {
$data = $val['Movimento']['data_vencimento'];
$dtVc = strtotime($data);
$dtHj = strtotime(date('Y-m-d'));
$dtVencendo = strtotime("+7 day", $dtHj);
if ($dtVc < $dtHj) {
$results[$key]['Movimento']['status'] = 'vencido';
} elseif ($dtVc <= $dtVencendo) {
$results[$key]['Movimento']['status'] = 'vc15dias';
} else {
$results[$key]['Movimento']['status'] = 'aberto';
}
}
if(isset($val['Movimento']['data_pagamento'])) {
$results[$key]['Movimento']['status'] = 'quitado';
}
}
return $results;
Pagination:
$options = array(
...
'order' => array('Movimento.status' => 'ASC')
);
$this->controller->paginate = $options;
$movimentos = $this->controller->paginate('Movimento');
I know this does not work because the field is created after the paginator call.
Can I make it work?
as I understand, you want to sort by data_pagamento and than by data_vencimento (has it the mysql-type date?)
so you don't need your afterFind-function for ordering, simply use:
'order' => array(
'Movimento.data_pagamento DESC',//first all rows with not-empty data_pagamento
'Movimento.data_vencimento DESC',// first all dates in the furthest future
)

Cakephp custom query pagination

I'm trying to use custom query in Cake then paginate the results with the code below:
$query = $this->Petition->query($sql);
I tried:
$petitions = $this->paginate($query);
and it doesn't work. Is there a way we can do this?
OK I wasn't clear enough: I need to use variable array fetched from custom query on pagination so I can use this for pagination in the view. Is there an easy way of doing this?
Below is my code:
function index() {
if ($this->Session->read('Auth.User.group_id') != 1) {
$commune_id = $this->Session->read('Auth.User.commune_id');
$commune_id = $this->Petition->Commune->findbyId($commune_id);
$commune_id = $this->Petition->Commune->find('all',array('conditions' => array('group' => $commune_id['Commune']['group'])));
$count = count($commune_id);
$i=1;
$sql = "SELECT * FROM `petitions` WHERE `commune_id` = ";
foreach($commune_id as $commune_ids){
if($i==1){
$sql .= $commune_ids['Commune']['id'];
}else{
$sql .= " OR `commune_id` = ".$commune_ids['Commune']['id'];
}
/*if($i != $count){
$this->paginate = array(
'or' => array(
array('Petition.commune_id LIKE' => $commune_ids['Commune']['id'] . ","),
//array('Petition.commune_id LIKE' => "," . $commune_ids['Commune']['id'] . ",")
),
'limit' => 10
);
}*/
$i++;
}
$query = $this->Petition->query($sql);
}
$this->Petition->recursive = 0;
$petitions = $this->paginate();
$this->set('petitions', $petitions);
}
you seriously need to read the pagination part in the cake book:
function index() {
$conditions = array();
if ($this->Auth->user('group_id') != 1) {
$commune_id = $this->Petition->Commune->findById($this->Auth->user('commune_id'));
$conditions['Petition.id'] = $this->Petition->Commune->find('list',array(
'fields'=>array('id','id')
'conditions' => array('group' => $commune_id['Commune']['group'])
));
}
$this->Petition->recursive = 0;
$petitions = $this->paginate('Petition',$conditions);
$this->set('petitions', $petitions);
}
something like that.
this is not how pagination works
you need to fill $this->validate with your conditions etc
and then use $this->paginate() plainly
see
http://book.cakephp.org/view/1232/Controller-Setup
also note the chapter about the custom query part if it is really(!) necessary.

Categories