Assign Variables to SQL command result - php

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 []

Related

code is returning data of one date only whereas i want data of every date

function practise()
{
$this->load->database();
$qry = mysql_query("select * from demmo");
if (mysql_num_rows($qry) > 0)
{
while ($row = mysql_fetch_array($qry))
{
$created = $row['created'];
//from here
$qry = mysql_query("select * from demmo where created = '$created'");
while ($res = mysql_fetch_array($qry))
{
$user_id = $res['id'];
$name = $res['name'];
$created2 = $res['created'];
$users[] = array('user_id' => $user_id, 'name' => $name);
}
$dotts[] = array('created' => $created2);
//till here
}
return array ($dotts,$users);
}
}
in demmo table i am trying to fetch data and showing that data according to date .the problem is that the code is only selecting one date from the table from created rows and showing that data only .fortunately data shown is not only last but the data with actual date.
You need to create an array and use array_push to get more than one result. Right now your code is only returning the last result of the while loop:
For example, to get all of the dates:
$dotts = array();
$allusers = array();
while ($res = mysql_fetch_array($qry))
{
$user_id = $res['id'];
$name = $res['name'];
$created2 = $res['created'];
array_push($dotts, $created2);
$users[] = array('user_id' => $user_id, 'name' => $name);
array_push($allusers, $users);
}
//
return array ($dotts,$allusers);
You need to create an array and use array_push function , then only it will have more than one value.
example:
create an empty array as
$allUser = array();
then after this line
$users[] = array('user_id' => $user_id, 'name' => $name);
use array_push as
array_push($allUser, $users);
}
return array($dots, $allUser);

Json wont response my array in php

I am trying to fetch multiple rows from my database and then encode them with json so I can access them in my Android application. I've successfully encoded an object but I couldn't find a way to do the same with an array. My code looks like:
if ($tag == 'friends') {
$id = $_POST['id'];
$friends = $db->getMyFriends($id);
if ($friends != false) {
// friends found
$result[] = array();
while($row = mysql_fetch_assoc($friends)){
$response[ "error"] = FALSE;
$result[] = array(
$response["friends"]["unique_id"] = $row["unique_id"],
$response["friends"]["name"] = $row["name"],
$response["friends"]["email"] = $row["email"]);
}
echo json_encode($response);
}
The code from getMyFriends($id) I have already tested and it works fine. It returns :
$result = mysql_fetch_array($result);
return $result;
When using a rest client passing the parameters:
Tag: friends
id: $id
this is the json response that I get:
{
"tag": "myfriends",
"error": false
}
, but no actual database data.
If anyone knows what I'm doing wrong, I'd really appreciate it, I've been browsing the internet for hours now.
If getMyFriends already have a $result = mysql_fetch_array($result);you don't need to fetch again.
You could simply:
$friends = $db->getMyFriends($id);
echo json_encode($friends);
But that will only return one friend, if you want all remove $result = mysql_fetch_array($result); from getMyFriends and return the pure mysql_result, then do something like:
$result = array();
while($row = mysql_fetch_assoc($friends)){
array_push($result,$row);
}
echo json_encode($result);
I tried this and it worked.
if($tag=='friends'){
$id = $_REQUEST['id'];
$friends = $db->getMyFriends($id);
if ($friends != false) {
// friends found
$result[] = array();
while($row = mysql_fetch_assoc($friends)){
$response[ "error"] = FALSE;
$result[] = array(
$response["friends"]["unique_id"] = $row["id"],
$response["friends"]["name"] = $row["name"],
$response["friends"]["email"] = $row["email"]
);
}
echo json_encode($result);
}
}

PHP create nested array and pass back with json_encode

I have the following, and while $data['details'] is being populated OK, there should be three results in $data['tests'], but "tests" isn't showing at all in the JSON result:
{"details":["Clinical result","Signature result"]}
$data = array();
while ($row = mysql_fetch_array($result)) {
$data['details'] = array($row['tests_clinical'], $row['signature']);
foreach($row['lab_test_group_fk'] as $group){
$data['tests'] = array($group);
}
}
echo json_encode($data);
If I change the above to the following then I get only the last record for $row['lab_test_group_fk'], not all three records for that column (hence the foreach loop as above):
while ($row = mysql_fetch_array($result)) {
$data['details'] = array($row['tests_clinical'], $row['signature']);
$data['tests'] = array($row['lab_test_group_fk']);
}
echo json_encode($data);
{"details":["Clinical result","Signature result"],"tests":["21"]}
What am I doing wrong here?
Thanks to Tamil Selvin this was the solution that worked for me:
$data = array();
while ($row = mysql_fetch_array($result)) {
$data['details'] = array($row['tests_clinical'], $row['signature']);
$data['tests'][] = array($row['lab_test_group_fk']);
}
echo json_encode($data);
Which returned:
{"details":["Clinical result","Signature result"],"tests":[["31"],["2"],["21"]]}
Try
$data = array();
while ($row = mysql_fetch_array($result)) {
$data[]['details'] = array($row['tests_clinical'], $row['signature']);
$data[]['tests'] = array($row['lab_test_group_fk']);
}
echo json_encode($data);
or
while ($row = mysql_fetch_array($result)) {
$data[] = array(
'details' => array($row['tests_clinical'], $row['signature']),
'tests' => array($row['lab_test_group_fk'])
);
}
echo json_encode($data);
$data['tests'] = array($group); means reassign $data['tests'] to a new value again.
Try $data['tests'][] = array($group); .
You are overwriting existing data of $data. You need some kind of array where you will put all your records. Try this
$data = array();
while ($row = mysql_fetch_array($result)) {
$record = array(); // this creates new record
$record['details'] = array($row['tests_clinical'], $row['signature']);
foreach($row['lab_test_group_fk'] as $group){
$record['tests'] = array($group);
}
$data[] = $record; // this adds record to data
}
echo json_encode($data);

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
);

Pass an array from controller to model in codeigniter

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

Categories