Laravel 5 WhereIn Not Working - php

I have no idea why my query is suddenly not working (although maybe it was never working to begin with). Is there anything wrong here?
My controller;
$dataset = $postcode_lookup->dataset; // will return "201502_postcode"
$postcode_extract = new PostcodeExtract;
$postcode_extract = $postcode_extract->setTableByDate($dataset);
foreach ($input as $column => $values) {
$postcode_extract->orWhere(function ($query) use ($column, $values) {
$query->whereIn($column, $values);
});
}
/*
* Temporarily print out the raw SQL...
*/
$sql = str_replace(['%', '?'], ['%%', "'%s'"], $postcode_extract->toSql());
$fullSql = vsprintf($sql, $postcode_extract->getBindings());
print_r($fullSql);
exit;
My model;
<?php namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class PostcodeExtract extends Model {
protected $connection = 'postcodes';
public function setTableByDate($selected_tablename)
{
$this->table = $selected_tablename;
// Return $this for method chaining
return $this;
}
public function getTable()
{
if (isset($this->table))
$this->setTableByDate($this->table);
return $this->table;
}
All that the print out of the raw sql is returning is select * from 201502_postcode and is just ignoring the rest of the query.
This is my $input array;
Array
(
[country] => Array
(
[0] => L93000001
[1] => M83000003
)
[county] => Array
(
[0] => 95
)
)
orWhere and whereIn is just being ignored it seems..
--- UPDATE ---
I didn't know about orWhereIn. But having tried this;
foreach ($input as $column => $values) {
$postcode_extract->orWhereIn($column, $values);
print "<br>";
print $column;
print "<br>";
print_r($values);
print "<br>";
}
I still get the same result. It's like this loop is being totally ignored - even though I can get these print's/print_r's to work. The raw SQL is still just select * from 201502_postcode.

Try this
$postcode_extract->orWhereIn($column, $values)
Also, if that doesnt work, try making the first one condition a whereIn and the rest a orWhereIn

Oh this is so frustratingly obvious I think I might cry...
foreach ($input as $column => $values) {
$postcode_extract = $postcode_extract->orWhereIn($column, $values);
}

Related

How to change this: [ [object1], [object2] ] to this: [ object1, object2 ] in php

controller:
$sold_fruits = [];
foreach ($clients as $client) {
$sold_fruits[] = $client->bought_fruits;
}
$supermarkets = [];
foreach ($sold_fruits as $sold_fruit) {
// HERE: I want to stop using this [0]
$supermarkets[] = $sold_fruit[0]->supermarket;
}
client model:
public function bought_fruits()
{
return $this->hasMany(BoughtFruits::class);
}
sold fruits model:
public function supermarket()
{
return $this->belongsTo(Supermarket::class);
}
In the first loop Im getting something like this:
[[obj1],[obj2]]. Thats why I have to use that [0] in there!
Is there any good way to stop using that [0]??
You can achieve your goal easily by using Laravel collection functions.
Use flatMap() when where there is an array of items in a property.
Use map() when there is only one item in a property.
In your case
There are many bought_fruits for a client, so use flatMap()
There is one supermarket for a bought_fruit, so use map()
$superMarkets = collect($clients)
->flatMap->bought_fruits
->map->supermarket;
You try to put index number in the array like these below.
$sold_fruits = [];
foreach($clients as $key => $value){
$sold_fruits[$key] = $value;
}
$supermarkets = [];
foreach($sold_fruits as $key => $value){
$supermarkets[$key] = $value;
}
NOTE: This is just to answer the question, scroll down more to see the other approach.

Why getPostParameters doesn't work on symfony 1.4?

I have a form in symfony 1.4 which are created for each competence. My forms was created with success. But when I try to save my form I can't. I go to see my action code and the function getPostParameters seem dosn't work. I use getParameterHolder to see what's wrong in my parameters but after I put the good value the getPostParameters function doesn't work.
This is what I get from getParameterHolder:
sfParameterHolder Object
([parameters:protected] => Array
(
[professionnal_competence] => Array
(
[rayon_competence3] => 24
[rayon_competence9] => 22
[rayon_competence19] => 32
)
[module] => professionnal_subregion
[action] => saveCompetenceRadius
)
)
And my function:
public function executeSaveCompetenceRadius(sfWebRequest $request) {
$user = $this->getUser()->getGuardUser();
$q = ProfessionnalCompetenceQuery::create()
->addSelect('pc.*')
->where('pc.professionnal_id= ?', $user->getId());
$res = $q->execute();
$values = $request->getPostParameters(['professionnal_competence']);
$test = $request->getParameterHolder();
var_dump($values); print_r($values); print_r($request->getParameterHolder());
exit;
foreach ($res as $professionnalCompetence) {
foreach ($values['professionnal_competence'] as $k => $val) {
if ($k == 'rayon_competence' . $professionnalCompetence->getCompetenceId()) {
$professionnalCompetence->setRayonCompetence($val);
$professionnalCompetence->save();
}
}
}
return $this->renderComponent('professionnal_subregion', 'competenceRadius');
// return "test";
//return $this->renderPartial('professionnal_subregion/competenceradius');
}
This is my form:
class ProfessionnalCompetenceRadiusForm extends BaseProfessionnalCompetenceForm {
public function configure()
{
unset($this['rayon_competence']);
$this->widgetSchema['rayon_competence'.$this->object->getCompetenceId()] = new sfWidgetFormSelectUISlider(array('max'=>50,'step'=>1));
$this->widgetSchema->setHelp('rayon_competence'.$this->object->getCompetenceId(),'en kilomètres');
$this->widgetSchema->setLabel('rayon_competence'.$this->object->getCompetenceId(),'rayon');
$this->setValidator('rayon_competence'.$this->object->getCompetenceId(), new sfValidatorInteger(array('max'=>50)));
}
}
Someone has an idea or can help me ?? Because I try lot of thing but without success. Thank in advance :).
I think the error hides in this line:
$values = $request->getPostParameters(['professionnal_competence']);
You're passing an array to a function that takes a string. Try removing the brackets around 'professionnal_competence'.
EDIT: Scratch that. getPostParameters takes no parameters. getPostParameter, on the other hand, takes two - the first of which is the field name - a string. So, your code should be:
$values = $request->getPostParameter('professionnal_competence');
The error is here:
$values = $request->getPostParameters(['professionnal_competence']);
The function sfWebRequest::getPostParameters doesn't actually take parameters.
You can either access this array with [...], or use getPostParameter, which allows "safe" deep access:
$val = $request->getPostParameter('a[b]');
// basically the same as, but with error checks:
$val = $request->getPostParameters()['a']['b'];

Accessing WP cron multidimensional array efficiently in PHP

I need to access multiple arrays, the problem lies when I get to the arrays I need like below, I can't access it traditionally because the key will be different every time.
I'm dealing with the following array:
Array
(
[oe_schedule_charge] => Array
(
[617cdb2797153d6fbb03536d429a525b] => Array
(
[schedule] =>
[args] => Array
(
[0] => Array
(
[id] => cus_2OPctP95LW8smv
[amount] => 12
)
)
)
)
)
There are going to be hundreds of these arrays and I need a way to efficiently access the data within them. I'm using the following code with expected output:
function printValuesByKey($array, $key) {
if (!is_array($array)) return;
if (isset($array[$key]))
echo $key .': '. $array[$key] .'<br>';
else
foreach ($array as $v)
printValuesByKey($v, $key);
}
$cron = _get_cron_array();
foreach( $cron as $time => $hook ) {
if (array_key_exists('oe_schedule_charge', $hook)) {
echo '<div>';
echo date('D F d Y', $time);
echo printValuesByKey($hook, 'amount');
echo printValuesByKey($hook, 'id');
echo '</div>';
}
}
But I've never had to deal with this much data, so I would like to take the proper precautions. Any light that can be shed on accessing a multidimensional array like this in an efficient way would be greatly appreciated.
I would consider loading it into an object, then writing member functions to get what you want.
class myclass {
private $_uniqueKey;
private $_schedule;
private $_args = array();
private $_amount = array();
private $_id = array();
public function __construct($arrayThing)
{
foreach($arrayThing['oe_schedule_charge'] as $uniqueKey => $dataArray)
{
$this->_uniqueKey = $uniqueKey;
$this->_schedule = $dataArray['schedule'];
$this->_args = $dataArray['args'];
}
$this->_afterConstruct();
}
private function _afterConstruct()
{
foreach($this->_args as $argItem)
{
if(isset($argItem['amount']) && isset($argItem['id']))
{
$this->_amount[] = $argItem['amount'];
$this->_id[] = $argItem['id'];
}
}
}
public function getUniqueKey()
{
return $this->_uniqueKey;
}
public function getSchedule()
{
return $this->_schedule;
}
public function getArgs()
{
return $this->_args;
}
public function printShitOut($time)
{
//You define this. But if you do a print_r( on the object, it will tell you all the items you need. )
}
//code would be like this:
$cron = _get_cron_array();
foreach( $cron as $time => $hook )
{
$obj = new myclass($hook);
$obj->printShitOut($time);
}

PHP object can not access variable

Using the following:
$last_book = tz_books::getLast($request->db, "WHERE book_id='{$request->book_id}'");
I get the following php object array,
[0] => tz_books Object
(
[db:tz_books:private] => com Object
[id] => 64BEC207-CA35-4BD2
[author_id] => 4F4755B4-0CE8-4251
[book_id] => 8FC22AA0-4A60-4BFC
[date_due] => variant Object
)
I then want to use the author_id, but for some reason it's not working.
Trying to use:
$tz_books->author_id;
Using print_r($last_book); prints the array to the console just fine. And Doing the following just to see if the correct variable was being used:
$author = $tz_books->author_id;
print_r($author);
Nothing is printed to the console, and even after digging through the php manual and trying a lot of alternatives, I can't seem to grab that variable. I'm hoping i'm making a rookie mistake and overlooking something stupid. Thank you for any help!
Edit: Class definition
private $db;
public $id;
public $author_id;
public $book_id;
public $date_due;
public function __construct($db, $values=null) {
$this->db = $db;
if ( $values != null ) {
foreach ( $values as $var => $value ) {
$this->$var = $value;
}
}
}
public static function retrieveAll($db, $where='', $order_by='') {
$result_list = array();
$query = 'SELECT '.
'id, '.
'author_id, '.
'book_id, '.
'date_due '.
"FROM tz_books $where $order_by";
$rs = $db->Execute($query);
while ( !$rs->EOF ) {
$result_list[] = new tz_books($db, array(
'id' => clean_id($rs->Fields['id']->Value),
'author_id' => clean_id($rs->Fields['author_id']->Value),
'book_id' => clean_id($rs->Fields['book_id']->Value),
'date_due' => $rs->Fields['date_due']->Value,
));
$rs->MoveNext();
}
$rs->Close();
return $result_list;
}
Your result object seems to be an array of books with 1 element.
Try
echo $tz_books[0]->author_id;
BTW, it also looks like you're escaping input by putting single quotes. This is not a reliable/recommended method. Use a database-specific escape function like this

decode mysql query before returning it to view

I'm running a query to mysql that returns encrypted data. I'd like, if possible, to decode the results before sending it to the view. It seems like better form to handle the decoding in the controller (or even the model) rather than inside the view.
I can't seem to wrap my head around how to do it, though.
I was thinking I could iterate through the object, decodode it, and push it to another array that would be sent to the view. Problem with this is I won't know (and need to keep) the indexes of the query.
So the query might return something like:
[id] => 742
[client_id] => 000105
[last] => dNXcw6mQPaGQ4rXfgIGJMq1pZ1dYAim0
[first] => dDF7VoO37qdtYoYKfp1ena5mjBXXU0K3dDlcq1ssSvCgpOx75y0A==
[middle] =>iXy6OWa48kCamViDZFv++K6okIkalC0am3OMPcBwK8sA==
[phone] => eRY3zBhAw2H8tKE
Any ideas?
Ended up with:
function name(){
$data['e_key']=$this->e_key;
$clid = $this->uri->segment(3);
$name = $this->Clients_model->getNameData('*','client_id='.$clid,'');
$nameArray= array();
foreach ($name->result() as $row){
$x = $row;
$keys = array('id','client_id');
$unenc = array();
foreach ($x as $key=>$value){
if(! in_array($key, $keys)){
$unenc[$key]=$this->encrypt->decode($value,$this->e_key);
}else{
$unenc[$key]=$value;
}
}
array_push($nameArray,$unenc);
}
$data['name'] = $nameArray;
$this->load->view('names/name_view',$data);
}
Assuming you know how to decrypt the data, it's but a matter of iterating over the object, decrypting the encrypted fields.
If $YOUR_OBJECT is your object and your function for decryption is decode() then the following code should do the trick.
// The keys corresponding to the encrypted fields
$encoded = array('last', 'first', 'middle', 'phone');
$decoded = array();
foreach($YOUR_OBJECT as $key => $value)
{
if (in_array($key, $encoded))
{
$decoded[$key] = decode($value);
}
}
if it's a particular index, you could decode it like
$result['last'] = base64_decode($result['last']);
or in the model, use mutators and accessors:
public function setUp() {
$this->setTableName('tablename');
$this->actAs('Timestampable');
$this->hasMutator('last', '_encode64');
$this->hasAccessor('last', '_decode64');
}
protected function _encode($value) {
$this->_set('last',base64_encode($value));
}
protected function _decode($value) {
return base64_decode($value); // not sure on this one - might have to
// return $this->set('last', base64_decode($value));
}

Categories