Using foreach loop with Query Builder in Yii 2 - php

For some reason this isn't working. The error I get is "Undefined index: cu_id" for the line
$cu_id = $rows['cu_id'];
I think I'm just totally using the querybuilder wrong with the foreach loop. Any help with the proper syntax for this? Thanks!
$query = new Query;
$query->select('cu_id')->from('cu_emails')->where(['creator_id' => $user_id, 'email' => $email]);
foreach ($query as $rows) {
$cu_id = $rows['cu_id'];
echo"CU ID: $cu_id<br /><br />";
}
Also I'm on the Yii 2 framework in case anyone missed that.

You should add all() or one() for getting the rows
$query = new Query;
$myModels= $query->select('cu_id')
->from('cu_emails')
->where(['creator_id' => $user_id, 'email' => $email])
->all();
and obtained the models in $myModels
foreach ($myModels as $rows) {
$cu_id = $rows['cu_id'];
echo"CU ID: $cu_id<br /><br />";
}

You query not run.
$query->all()
and then foreach records
or
$query->one()
and get data from one record
$query = new Query;
$query->select('cu_id')->from('cu_emails')->where(['creator_id' => $user_id, 'email' => $email])
$results = $query->all();
foreach ($results as $rows) {
$cu_id = $rows['cu_id'];
echo"CU ID: $cu_id<br /><br />";
}

Related

Codeigniter transferring data from one table to another using for loop

I am trying to move data from one table to another in my model. In the first two lines I am getting all of the rows in my 'cart' table that match the username. I am now trying to iterate through all of these and match the product ID to the product ID in my 'product' table. I am then trying to format the data to fit my new table called 'sold'. However I am getting an error. I think the syntax of $q->id, $q->product_name etc is wrong. I know you can usually use that in the view but it does not work in the model. Do you know what the correct syntax would be to do this?
function checkout($username){
$this->db->where('username', $username);
$query = $this->db->get('cart');
//$data = array();
foreach ($query as $q){
$product = $this->db->get_where('product', array('id' => $q->id));
$arr['product_id'] = $product->id;
$arr['product_brand'] = $product->item_brand;
$arr['product_name'] = $product->item_name;
$arr['product_image'] = $product->item_image_url;
$arr['product_price'] = $product->item_price;
$arr['product_size'] = $product->item_size;
$arr['name_of_seller'] = $product->name_of_lister;
$arr['name_of_buyer'] = $this->session->userdata('username');
$this->db->insert('sold', $arr);
}
//Deletes the items out of the cart
// $this->db->delete('cart');
}
This is the error message I am getting
You have to use result() to get the data in the the $query variable.
$query = $this->db->get('cart')->result();
In the same way, also change the second query.
$product = $this->db->get_where('product', array('id' => $q->id))->result();
See if this helps you.
function checkout($username){
$this->db->where('username', $username);
$query = $this->db->get('cart');
if ($query->num_rows()>0) {
$qdata = $query->result_array();
foreach ($qdata as $key => $qdvalue) {
$this->db->where('id', $qdvalue['id']);
$product = $this->db->get('product');
$pdata = $product->row_array()
$inarray = array(
'product_id' => $pdata['id'],
'product_brand' => $pdata['item_brand'],
'product_name' => $pdata['item_name'],
'product_image' => $pdata['item_image_url'],
'product_price' => $pdata['item_price'],
'product_size' => $pdata['item_size'],
'name_of_seller' => $pdata['name_of_lister'],
'name_of_buyer' => $this->session->userdata('username')
);
$this->db->insert('sold', $inarray);
}//end of foreach
}//end of if query
}//end of checkout function
I rewrite your function if all the column values right then It will work.
And I will suggest you to use transactions for this type of db events.

How can I pass on an array of data from the model to the controller and then back to the model?

I'm trying to select rows from my DB table based on information I get from the other rows(previous query). The trouble I'm having is converting the $query->result_array(); in the controller to use it in the model again and subsequently the view.
I've tried to do a foreach loop and returning the $query->result_array(); from the model, this turned out to be problematic as it didn't fit the different stages I have on my website(I have several stages of content).
controller.php
public function firststage() {
$this->load->model('Model');
$get_stage = $_GET["stg"];
$get_results = $this->Model->get_stage_id($get_stage);
foreach ($get_results as $results) {
$id = $results["id"];
}
$data['result'] = $this->Model->stage_results($get_stage, $id);
$this->load->view('stage_view', $data);
}
model.php
public function get_stage_id($get_stage) {
$this->db->where('stage_parent', $get_stage);
$query = $this->db->get('stages');
return $query->result_array();
}
public function stage_results($get_stage, $id) {
$this->db->where('stage_id', $get_stage);
$this->db->where('stage_id', $id);
$query = $this->db->get('stage_contents');
foreach ($query->result_array() as $row) {
$rows[] = array(
'id' => $row["id"],
'name' => $row["name"]
);
}
return $rows;
}
Expected the output selection to be based on the first query result, instead I get the Undefined variable: rows when I run all of it. I don't think my view is relevant to this question, but please let me know if you think otherwise!
you get the error
Undefined variable: $rows
because your query doesn't return any result, therefore $rows is not defined
you can resolve this checking if there are rows returned:
if($query->num_rows()){
foreach ($query->result_array() as $row) {
$rows[] = array(
'id' => $row["ID"],
'name' => $row["name"]
);
}
}else {$rows='no records found';}
print_r($rows);die;
this prints either the array (if there are results), or 'no records'
or simply do:
$rows = array();
foreach ($query->result_array() as $row) {
$rows[] = array(
'id' => $row["ID"],
'name' => $row["name"]
);
}
then you get an empty array if there are no results

renaming array using foreach on controller and view:

I'm having a problem, I tried renaming my $query->result_array() using foreach on my controller and called it in view using another foreach to display the result from $query->result_array();
Here's how I did it.
My controller:
I have this user-defined function named logs(), I have a query inside and used $query->result_array() to get the results. Then I renamed it using foreach{} like this code below:
$result = array();
foreach ($query->result_array() as $row) {
$result = array(
"id" => $row['id'],
"name" => $row['name'],
"status" => $row['status'],
"time" => $row['time']
);
}
return $result;
Then I created another user-defined function named filtered_logs() to filter the result from logs() *I filtered it because I have multiple tables to LEFT JOIN it with.
$filtered = array();
$logs = $this->logs();
if ($logs['status'] == "ok") {
$query = $this->db->query("SELECT * FROM table a
LEFT JOIN table b
ON a.image = b.image
LEFT JOIN ....ON...
WHERE a.id = '".$logs['id']."'");
foreach ($query->result_array() as $row){
$filtered = array(
"path" => $row['path'],
"grade" => $row['grade'],
"time" => $logs['time'],
);
}
}
Sending these results to view I used this method, placed on the index of the controller.
$data['logs'] = $this->filtered_logs();
$this->load->view('pages', $data);
Then displayed it on view using these codes:
<?php
foreach ($logs as $row) {
echo $row['id']." </br>";
echo $row['status']." </br>";
echo $row['time']." </br>";
}
?>
but when I do use this way of handling result_array, it gives me an error saying " Illegal string offset '' "
Can someone help me or tell me if there's another way of displaying the results of my queries?
I guess you are missing "[]" after $result array where you are feeding data in it in for each loop and it is causing this error.
It should be like this:
$result = array();
foreach ($query->result_array() as $row) {
$result[] = array(
"id" => $row['id'],
"name" => $row['name'],
"status" => $row['status'],
"time" => $row['time']
);
}
return $result;
This is just an other way of displaying the results try it.
<?php
foreach ($logs as $row) {
echo $row->id." </br>";
echo $row->status." </br>";
echo $row->time." </br>";
}
?>

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

how to select specific records from mongodb using php

I am using the following code:
foreach ($record as $doc)
{
$groupIds[] = $doc['groupId'];
}
$gpids = "'".implode("','",array_unique($groupIds))."'";
$collection5 = $db->chat;
$cursor = $collection5->find(array('groupId' => array('$in' => array($gpids))));
foreach($cursor as $res)
{
print_r($res);
}
but no results will come. Please help me.
That is because your $gpids is a string and you end up putting one element array in the $in query. This should work:
$collection5->find(array('groupId' => array('$in' => array_unique($groupIds))));

Categories