Pass an array from controller to model in codeigniter - php

I am doing a project in Codeigniter. Here I fetch the latest 10 mails from my gmail id using imap.Here I want to take the from field of fetched mail and i want to check whether the from field of fetched mail is in my database table('clients'). Here I stored the 10 from field of fetched mail to array and passed it to model,where the checking is takingplace and returns the matching field name. But it is not working for me.
My controller function is:
if ($mbox = imap_open($authhost, $user, $pass)) {
$emails = imap_search($mbox, 'ALL');
$some = imap_search($mbox, 'SUBJECT "Suspicious sign in prevented"', SE_UID);
$MC = imap_check($mbox);
$inbox = $MC->Nmsgs;
$inboxs = $inbox - 9;
if ($emails) {
$data['overview'] = imap_fetch_overview($mbox, "$inboxs,$inboxs:$inbox", 0);
$i = 0;
foreach ($data['overview'] as $i => $val) {
$from[$i] = $val->from;
$i++;
}
$data['result'] = $this->crm_model->get_names($from);
foreach ($data['result'] as $row) {
echo $row->name;echo "<br/>";
}
}
imap_close($mbox);
}
And my model function is:
function get_names($from) {
$this->db->select('name');
$this->db->from('clients');
$this->db->where_in('name', $from);
$query = $this->db->get();
return $query->result();
}
But when I used the above model function like below, it returns the value
function get_names() {
$options = array(
'0' => 'Job Openings',
'1' => 'Offers',
'2' => 'Techgig',
'3' => 'Australia',
);
$this->db->select('name');
$this->db->from('clients');
$this->db->where_in('name', $options);
$query = $this->db->get();
return $query->result();
}
I think the problem is with passing value from controller to model. Can anyone help me. Thanks in advance

While executing any query in database using where_in (list of comma separated values),
the list of values should be like this array:
$options = array('Hello', 'World!', 'Beautiful', 'Day!');
Not like this:
$options = array('0' => 'Job Openings','1' => 'Offers','2' => 'Techgig','3' =>'Australia',);
to do this you should implode this array!
$opt=implode(",",$options);
and pass this $opt array to WHERE_IN()
Hope this will solve your problem !

You don't have to use $i..
if ($emails) {
$data['overview'] = imap_fetch_overview($mbox, "$inboxs,$inboxs:$inbox", 0);
// $i = 0;
foreach ($data['overview'] as $val) {
$from[] = $val->from;
//$i++;
}
$data['result'] = $this->crm_model->get_names($from);
foreach ($data['result'] as $row) {
echo $row->name;echo "<br/>";
}
}
Do these changes and check

Related

How to get data from database that result as an array in model codeigniter

I want to make a query that results like this in codeigniter MODEL:
$caldata = array (
15 => 'yes',
17 => 'no'
);
Is that possible to do?
Take NOTE: The 15,17 and yes,no are in the same database table.
There is no core helper function to achieve what you want in CI. But you can create your own helper function:
function pluck($arr = [], $val = '', $key = '')
{
// val - label for value in array
// key - label for key in array
$result = [];
foreach ($arr as $value) {
if(!empty($key)){
$result[$value[$key]] = $value[$val];
}else{
$result[] = $value[$val];
}
}
return $result;
}
you can use result_array() function so you can have something like:
$query = $this->db->select('id,answer')->from('users')->get();
$result = $query->result_array();
print_r($result);
After that you have your array and you can make the $key => $value relation of the fields
After a long search i found an answer. Sample way to do this:
$query = $this->db->select('start_date, class')->from('event')->like('start_date', "$year-$month", 'after')->get();
$datavariable = $query->result();
$caldata = array();
foreach($datavariable as $row){
$caldata[substr($row->start_date,8,2)] = $row->class;
}

Assign Variables to SQL command result

Succesfully solved: Working code is noted at the bottom of this Post.
I'm currently trying to run a SQL command to grab all the data out of a database table and send it over a API call using the variable names.
The problem I'm having is assigning the values of the fields under "$row" to separate variables so I can then place them in my foreach loop and send them all over to the API call. Can anyone enlighten me to what I'm doing wrong
I'm sure the line that I'm going wrong is my commandbuilder and then assigning the variables to the data inside row.
I feel like the problem line could be
while ($row = mysql_fetch_assoc()) {
$emails = $row['email_address'];
$names = $row['forename'];
}
the full code is below.
public function actionImportSubscribers($cm_list_id){
//need to pass through cm_list_id instead
$cm_list_id = Yii::app()->getRequest()->getQuery('cm_list_id');
$model =$this->loadModelList($cm_list_id);
$listID = $model->cm_list->cm_list_id;
$row = Yii::app()->db->createCommand()
->select('email_address, forename')
->from('tbl_cm_subscribers')
->where('cm_list_id=:id', array(':id' => $cm_list_id))
->queryAll();
while ($row = mysql_fetch_assoc()) {
$emails = $row['email_address'];
$names = $row['forename'];
}
$customFieldArray = array();
$addFieldsToList = array();
foreach (array_combine($emails, $names) as $name => $email) {
$addFieldsToList[] = array('EmailAddress' => $email,'Name' => $name,'CustomFields' => $customFieldArray);
}
$auth = array('api_key' => '');
$wrap = new CS_REST_Subscribers($listID, $auth);
$result = $wrap->import(array($addFieldsToList), false);
Working code is below
public function actionImportSubscribers($cm_list_id){
//need to pass through cm_list_id instead
$cm_list_id = Yii::app()->getRequest()->getQuery('cm_list_id');
$model =$this->loadModelList($cm_list_id);
$listID = $model->cm_list->cm_list_id;
$result = Yii::app()->db->createCommand()
->select('email_address, forename')
->from('tbl_cm_subscribers')
->where('cm_list_id=:id', array(':id' => $cm_list_id))
->queryAll();
$emails=array();
$names=array();
foreach ($result as $row) {
$emails[] = $row['email_address'];
$names[] = $row['forename'];
}
require_once 'protected/extensions/createsend-php-5.0.1/csrest_subscribers.php';
$auth = array('api_key' => '');
foreach (array_combine($emails, $names) as $email => $name) {
$wrap = new CS_REST_Subscribers($listID, $auth);
$result = $wrap->import(array(
array(
'EmailAddress' => $email,
'Name' => $name,
),
), false);
}
echo "Result of POST /api/v3.1/subscribers/{list id}/import.{format}\n<br />";
if($result->was_successful()) {
echo "Subscribed with results <pre>";
var_dump($result->response);
} else {
echo 'Failed with code '.$result->http_status_code."\n<br /><pre>";
var_dump($result->response);
echo '</pre>';
if($result->response->ResultData->TotalExistingSubscribers > 0) {
echo 'Updated '.$result->response->ResultData->TotalExistingSubscribers.' existing subscribers in the list';
} else if($result->response->ResultData->TotalNewSubscribers > 0) {
echo 'Added '.$result->response->ResultData->TotalNewSubscribers.' to the list';
} else if(count($result->response->ResultData->DuplicateEmailsInSubmission) > 0) {
echo $result->response->ResultData->DuplicateEmailsInSubmission.' were duplicated in the provided array.';
}
echo 'The following emails failed to import correctly.<pre>';
var_dump($result->response->ResultData->FailureDetails);
}
echo '</pre>';
// }
}
I don't know if this solving your problem but you have few errors there.
mysql_fetch_assoc() requires param , resource returned from mysql_query function.
In part where you creating $emails and $names variables you doing that like if you trying to create array but you will get always single value in that way how you have done it. This is example if you will use mysql_fetch_assoc, you can't combine queryAll() with mysql_fetch_assoc
$emails=array();
$names=array();
$result=mysql_query("SELECT email_address, forename FROM tbl_cm_subscribers where cm_list_id='$cm_list_id'");
while ($row = mysql_fetch_assoc($result)) {
$emails[] = $row['email_address'];
$names[] = $row['forename'];
}
queryAll() method returns array, I don't know Yii but I suppose this is what you need to do
$result = Yii::app()->db->createCommand()
->select('email_address, forename')
->from('tbl_cm_subscribers')
->where('cm_list_id=:id', array(':id' => $cm_list_id))
->queryAll();
$emails=array();
$names=array();
foreach ($result as $row) {
$emails[] = $row['email_address'];
$names[] = $row['forename'];
}
Or if you don't need array of results then use $emails and $names without []

When i run cron for a database function it returns me the same value

here is the cron code:
function blablabla_cron() {
$i=1;
do {
$gad = blablabla();
$i++;
}while ($i<6);
}
this code returns me always the same value of the table.
and here is the code of the blablabla function
function blablabla() {
// Begin building the query.
$query = db_select('watchdog', 'th')
->extend('PagerDefault')
->orderBy('wid')
->fields('th')
->limit(8)
// Fetch the result set.
$result = $query->execute();
// Loop through each item and add to the $rows array.
foreach ($result as $row) {
$Severities = unserialize($row->variables);
if($Severities['%type']) {
$rows[] = array(
$row -> wid,
$Severities['%type'],
);
}
}
// Headers for theme_table().
$header = array('ID', 'Message');
// Format output.
$output = theme('table', array('header' => $header, 'rows' => $rows)) . theme('pager');
return $output;
}
what i must do in order when cron runs it will show all the values of the table?
Pass that $i to blabla($i) and then use it inside that function to query different range of row your query returns:
Instead of:
->limit(8);
Use:
->range(($i-1)*8,8);
That is...if I figured out correctly what you want to achieve here.
https://api.drupal.org/comment/13489#comment-13489

codeigniter controller input Hebrew letters

I have a function in the controller that gets a string and then queries the database (via the model) for records that have this string as their name. This works fine with English but I have a problem when the input is in Hebrew. When I echo the string I see something like %D7%91 and the query fails.
All database tables entries are defined as utf8_general_ci.
My controller code:
function get_records_by_name($name)
{
echo 'searching for: '.$name.'</br>';
$keys = new DMkeys() ;
$query = $keys->get_keys();
$arr = array();
$count = 0;
foreach ($query->result() as $row)
{
if(stristr($row->name, $name) != FALSE)
{
$arr[] = $row->name;
$count++;
echo $row->name.'</br>';
}
}
$result = array('count' => $count, 'list' => $arr);
echo json_encode($result) ;
}
My model code:
function get_keys()
{
$query = $this->db->get('keys');
return $query;
}
Thanks,
Simon
You need to decode the variable before using it, try:
$name = urldecode($name);

How to access array computer by a function within Codeigniter?

I have a function as follow:
function get_employee_information()
{
$this->db
->select('id, name');
$query = $this->db->get('sales_people');
$employee_names = array();
$employee_ids = array();
foreach ($query->result() as $row) {
$employee_names[$row->id] = $row->name;
$employee_ids[] = $row->id;
}
}
I'm trying to access this data from within an output to template, like this:
$this->get_employee_information();
$output = $this->template->write_view('main', 'records', array(
'employee_names' => $employee_names,
'employee_ids' => $employee_ids,
), false);
Yet this isn't displaying anything. I feel like this is something small and I should know better. When I tun print_r($arrayname) on either array WITHIN the function, I get the suspected array values. When I print_r OUTSIDE of the function, it returns nothing.
Your function is not returning anything. Add the return shown below.
function get_employee_information()
{
$this->db->select('id, name');
$query = $this->db->get('sales_people');
$employee_names = array();
$employee_ids = array();
foreach ($query->result() as $row) {
$employee_names[$row->id] = $row->name;
$employee_ids[] = $row->id;
}
return array(
'employee_names'=>$employee_names,
'employee_ids'=>$employee_ids,
);
}
You are not setting the return value of the function to a variable
$employee_info = $this->get_employee_information();
$output =
$this->template->write_view(
'main', 'records',
array(
'employee_names' => $employee_info['employee_names'],
'employee_ids' => $employee_info['employee_ids'],
),
false
);

Categories