Yii using a variable with an IN condition - php

I am trying to pull information into a page using my model. The issue is that I need to use an IN condition on my mysql using a variable.
Here is the code I use currently
$list_id = '1,3';
$clients = ListSubscriber::model()->findAll(array('condition'=>'list_id IN (:list_id)','params'=>array(':list_id'=>$list_id)));
I won't necessarily know how many numbers will be stored within $list_id, hence the need for a variable to work with the IN.
The code does execute without errors, but only seems to return the values for the first number of $list_id, so in this case it only finds users where the list_id = 1.
Any help is appreciated. I have found this question Yii addInCondition
However they are using static values, which does not resolve my issue.
When I do use static values, the code executes with results as expected.

You can use addInCondition :
$list_id = '1,3';
$criteria = new CDbCriteria();
$arr_list_id = explode(",",$list_id);
$criteria->addInCondition("list_id ", $arr_list_id );
$clients = ListSubscriber::model()->findAll($criteria);

$list_ids = array(1,3);
$clients = ListSubscriber::model()->findAllByAttributes(array('list_id'=>$list_ids));

Related

Trying to print values in multidimensional array to form as presets values

I'm currently working on a project where my current goal is to print information about the specific user on the final checkout form inputs.
First off I gather the information of the specific user through a public function:
public function getUserAddress($dbh)
{
$sql = "SELECT street, zip, city FROM address WHERE user_id=:user";
$stmt = $dbh->prepare($sql);
$stmt->bindParam(':user', $this->uid);
$stmt->execute();
$userAddress = $stmt->fetchAll(PDO::FETCH_ASSOC);
$this->userAddress = $userAddress;
return $this->userAddress;
}
Then I store the information in a variable I call $userAddress
$userAddress = $user->getUserAddress($dbh);
Since the user has two addresses, both with a "Street", "City" & "Zip" I'm storing both arrays in $templateData. This way I can specify what index should be printed out in which input tag instead of having to create a new function for each slot.
$templateData['user']['address'] = $userAdress['street']." ".$userAddress['city']." ".$userAddress['zip'];
However, printing these out seems near impossible. When I var_dump
$templateData['user']['address']
I only seem to be getting 2 empty strings and nothing else.
This is just code from my Checkout.controller but somehow the information doesn't seem to be found in my template page. All routes and includes are correct so dw about that.
I'm quite new to all this so I'd appreciate any help I can get!
Image of how the information should be presented https://gyazo.com/40fa06832207bd785ee038af4962bb1e
So in this case: "Postort" = "City" & "Gatuadress" = "Street"
PDO::fetchAll(PDO::FETCH_ASSOC) will return an array of associative arrays; so to access the individual elements you need something like:
$userAdress[0]['street']." ".$userAddress[0]['city']." ".$userAddress[0]['zip']
I could alaways define every single one of them specifically although it seems far fetched. Something like this:
$templateData['user']['address'][0]['street'] = $userAddress[0]['street'];
$templateData['user']['address'][0]['city'] = $userAddress[0]['city'];
$templateData['user']['address'][0]['zip'] = $userAddress[0]['zip'];
$templateData['user']['address'][1]['street'] = $userAddress[1]['street'];
$templateData['user']['address'][1]['city'] = $userAddress[1]['city'];
$templateData['user']['address'][1]['zip'] = $userAddress[1]['zip'];
I'm basically looking for another solution which doesn't require so much repetition.

TransactionSearchBasic() amountPaid & amountRemaining Null

When i use the following php code with the 2016 Netsuite toolkit to retrieve an invoice, the returned object has the properties amountPaid & amountRemaining but they are both Null. Why are they not showing the values they should be, why include them if only always empty, and whats the best way around this ?
$search = new TransactionSearchBasic();
$SearchLongField = new SearchLongField();
$SearchLongField->searchValue = $internalId;
$SearchLongField->operator = "equalTo";
$search->internalIdNumber = $SearchLongField;
$_csearch = new RecordRef();
$_csearch->type = 'customer';
$_csearch->internalId = $customerId;
$custSearchField = new SearchMultiSelectField();
$custSearchField->searchValue[] = $_csearch;
$custSearchField->operator = "anyOf";
$search->entity = $custSearchField;
$request = new SearchRequest();
$request->searchRecord = $search;
$searchResponse = $this->service->search($request);
$result = json_decode(json_encode($searchResponse), true);
// Return results
return $result;
So though I have not received any outside responses yet, after further research and experimentation Ive come tho the belief that NS will return a full object structure for each data type whether all the properties (keys) are set or not.
And in the case of TransactionSearchBasic and other SearchBasic extensions it only returns a 'basic' subset of common fields used, the others just have Null as their value.
To get these extra data fields populated you have to request them with TransactionSearchAdvanced, and either a saved search or using the columns field. The flip side of this is as far as i can tell, you have to specify all columns you want, there's no way to just add a few extra fields to a Basic search.
NS API documentation is almost non-existent, but i work off this:
http://www.netsuite.com/help/helpcenter/en_US/srbrowser/Browser2016_2/schema/search/transactionsearchadvanced.html?mode=package
and recently found this:
https://usergroup.netsuite.com/users/

FindAll() not working in Yii Framework

My model name is Sales.
$allSales = Sales::model()->findAll();
$allSales return nothing (Blank). But its working my local computer(Ubuntu) and Not working on live server (Mac).
$allSales2 = Sales::model()->findAll("id < 2000");
$allSales2 is working on both server
Please help me. Thanks in advance.
(Blank) is vague, but if the page itself is blank when it loads you are likely seeing an out of memory error. This is common with a large number of active records being queried at once. Check the php_error.log file and the respective memory limits in php.ini on each server.
You can also try to use CDataProviderIterator to fetch all the models, instead of findAll().
$dataProvider = new CActiveDataProvider('Sales');
$allSales = new CDataProviderIterator($dataProvider);
foreach ($allSales as $model) {
//do whatever
}
If your issue IS a memory problem, this should get around it.
If not, add var_dump($allSales); to your original code, and report the results from the live server.
You need pass the conditions as array. Try like this
$allSales2 = Sales::model()->findAll(
array(
"condition" => "id < 2000"
)
);
If you do not like to use array in findAll then can use CDbCriteria like below
$criteria = new CDbCriteria;
$criteria->select = '*';
$criteria->condition = 'id < 2000';
$allSales2 = Sales::model()->findAll($criteria);

Using Simple HTML DOM to extract an 'a' URL

I have this code for scraping team names from a table
$url = 'http://fantasy.premierleague.com/my-leagues/303/standings/';
$html = #file_get_html($url);
//Cut out the table
$FullTable = $html->find('table[class=ismStandingsTable]',0);
//get the text from the 3rd cell in the row
$teamname = $FullTable->find('td',2)->innertext;
echo $teamname;
This much works.. and gives this output....
Why Always Me?
But when I add these lines..
$teamdetails = $teamname->find('a')->href;
echo $teamdetails;
I get completely blank output.
Any idea why? I am trying to get the /entry/110291/event-history/33/ as one variable, and the Why Always Me? as another.
Instead do this:
$tdhtml = DOMDocument::loadHTML($teamdetails);
$link = $tdhtml->getElementsByTagName('a');
$url = $link->item(0)->attributes->getNamedItem('href')->nodeValue;
$teamdetails = $teamname->find('a')->href;
^^^^^^^^^---- never defined in your code
I also fail to see how your "works" code could possibly work. You don't define $teamname in there either, so all you'd never get is the output of a null/undefined variable, which is...no output all.
Marc B is right, I get that you don't have to initialize a variable, but he is saying you are trying to access a property of said variable:
$teamdetails = $teamname->find('a')->href;
^^^^^^^^^---- never defined in your code
This is essentially:
$teamname = null;
$teamname->find('a')->href;
The problem in your example is that $teamname is a string and you're treating it like a simple_html_dom_node

How to get results from "Elastica_ResultSet" object

I am using the "elastica" php client for ElasticSearch.
I'm a bit new to OO-programming, especially in php.
However, I have managed to search my elasticsearch server using the elastica php client and store the response in an "Elastica_ResultSet" object. I have had no luck accessing the contents of that object whatsoever.
I would like to be able to list the total number of results, find an elasticsearch record id of a result and get the full content of an elasticsearch record for that result.
The Elastica class reference can be found here http://ruflin.github.com/Elastica/api/index.html , although I don't know what to do with it.
Here is the php code I have been using to get this far:
<?php
function __autoload_elastica ($class) {
$path = str_replace('_', '/', $class);
if (file_exists('extentions/' . $path . '.php')) {
require_once('extentions/' . $path . '.php');
//echo "$path EXISTS!!!";
}
}
spl_autoload_register('__autoload_elastica');
// New ES Client
$client = new Elastica_Client();
// Set Index
$index = $client->getIndex('test1');
// Set Document Type
$type = $index->getType('user');
// Perform Search
$resultSet = $index->search('halo');
?>
So basicaly you can use var_export to output your resultset
But in general the elastica search returns a Elastica_ResultSet object which has several attributes you can use like count, totalHits facets and so on.
and also holds an array of Elastica_Result objects these can be accessed either by calling the Elastica_ResultSet getResults() method or by using the current() and next() methods or by simply using the php foreach function
The Elastica_Result the data of the results and also has several methods you can use.
getId(), getVersion(), getData() and so on.
// Set Document Type
$type = $index->getType('user');
// Perform Search
$resultSet = $index->search('halo');
// Get IDs
$resultIDs = array();
foreach($resultSet as $result){
$resultIDs[] = $result->getId();
}
I would like to let you know something that was a bit hard for me to get.
The query and the sorting of results
// Set the query terms for your search
$queryTerm = new Elastica_Query_Terms();
$queryTerm->setTerms('user', array("test", "test1"));
// Create the sorting array
$sort = array("user" => array("order" => "desc"));
// Create the query
$query = Elastica_Query::create($queryTerm);
// Set the sorting to the query
$query->setSort($sort);
// Perform the search
$resultSet = $index->search($query);
Hope this helps
After a couple of months OO practise, it seemed performing a simple var_dump($resultSet) would have provided me with the structure and contents of the returned object... can't believe that nobody made any suggestions for such a basic question ;)

Categories