CakePHP find query using %like% with spaces - mysql

I'm trying to query a page based on either a category ID or sub category name.
The variable $cat will either have an integer or varchar grabbed from my database.
I've been using cakephp 1.3 with a sql find all articles with a category of $cat OR sub-category LIKE $cat
It works great but a problem arises when $cat has a space between words, "google forms".
I've looked through this site and tried a number of methods with no luck. Appreciate any advice.
Here's my controller routines:
$cat = Sanitize::escape($cat);
$cat = trim($cat);
$title_a = str_replace($cat, "%".$cat."%", $cat);
$a_t = str_replace('"', $title_a, $title_a);
//var_dump($cat);
if(!empty($cat))
{
$sqlConditions = array('OR'=>array('Article.categories LIKE' => $a_t, 'Article.event_category_id' => $cat));
$sqlParams = array('conditions'=>$sqlConditions);
$catdata=$this->Article->find('all',$sqlParams);
return $catdata;
}
I've tried many different alternatives:
RLIKE instead of LIKE
Different query using MATCH
$sqlConditions = array(
'OR' => array(
'MATCH(Article.categories AGAINST(? IN BOOLEAN MODE)' => $cat,
'MATCH(Article.event_category_id) AGAINST(? IN BOOLEAN MODE)' => $cat
)
);
$sqlConditions = array('OR'=>array('Article.categories LIKE' => "%".$cat."%", 'Article.event_category_id' => $cat));

I think a decent solution would be to remove all of the spaces and make the characters of $cat lower case.
$likeCat = strtolower(str_replace(' ', '', trim($cat)));
$sqlConditions = array(
'OR'=> array(
'LOWER(REPLACE(Article.categories, ' ', ''))' => $likeCat,
'Article.event_category_id' => $cat
)
);

Related

CakePHP 3 quoting function names defined in 'fields' configuration of my find() call

I am querying a database table conveniently named order and because of that I had to set 'quoteIdentifiers' => true in my app.php configuration. However, when I'm putting function names into the fields configuration of my find() call, CakePHP quotes them too.
$orders->find('all', array(
'fields' => array(
'DATE(Orders.date_added)',
'COUNT(*)',
),
'conditions' => array(
'Orders.order_status_id <>' => 0,
),
'group' => array(
'DATE(Orders.date_added)',
),
));
The query above ends up calling
SELECT <...>, `DATE(Orders.date_added)` FROM `order` <...>
which obviously throws an error.
I googled a lot, tried this:
$orders = $orders->find('all', array(
'conditions' => array(
'Orders.order_status_id <>' => 0,
),
'group' => array(
'DATE(Orders.date_added)',
),
))->select(function($exp) {
return $exp->count('*');
});
and that didn't work either, throwing me some array_combine error.
Is there any way for me to un-quote those function names, while keeping the rest of the query quoted automatically? Here's what I'm trying to accomplish:
SELECT <...>, DATE(Orders.date_added) FROM `order` <...>
Please help.
You should use function expressions, they will not be quoted, except for arguments that are explicitly being defined as identifiers:
$query = $orders->find();
$query
->select([
'date' => $query->func()->DATE([
'Orders.date_added' => 'identifier'
]),
'count' => $query->func()->count('*')
])
->where([
'Orders.order_status_id <>' => 0
])
->group([
$query->func()->DATE([
'Orders.date_added' => 'identifier'
])
]);
I'd generally suggest that you use expressions instead of passing raw SQL snippets wherever possible, it makes generating SQL more flexible, and more cross-schema compatible.
See also
Cookbook > Database Access & ORM > Query Builder > Using SQL Functions

Datatables : Make a parallel request in another table using ServerSide

EDIT : I found the solution by replacing the SSP class by a customized SSP class I've found here : https://github.com/emran/ssp
I don't know if it's an understandable title, but here is my problem :
I have a DB-table (called projects) that needs to be inserted in a datatable. I've no problem to make a call using ServerSide and get results in the datatable.
But, for each project (each row), there is a project creator (column creator_id in the projects DB-table). What I need to do is to make a request to the creators DB-table in order to get the firstname/lastname of the creator, each time I get a row from the projects DB-table. Is that make sense?
Here is the code I use :
$table = 'projects';
$primaryKey = 'project_id';
$columns = array(
array(
'db' => 'project_id',
'dt' => 'DT_RowId',
'formatter' => function( $d, $row ) {
return $d;
}
),
array( 'db' => 'creator_id',
'dt' => 'creator',
'formatter' => function( $d, $row ) {
// Here I need to make a call to the creators DB-table and return the $creator_name value
return $creator_name;
}
)
);
// SQL server connection information
$sql_details = array(
'user' => '',
'pass' => '',
'db' => '',
'host' => ''
);
require(BASE_DIR.'/lib/dataTables/ssp.class.php');
$result = SSP::simple($_GET, $sql_details, $table, $primaryKey, $columns);
You can use formatter property to make a separate SQL query but it will affect performance greatly by increasing script response time.
Instead you can use the following trick when using ssp.class.php with sub-queries instead of table name to use GROUP BY, JOIN, etc.
<?php
$table = <<<EOT
(
SELECT projects.project_id, creators.creator_id, creators.creator_name
FROM projects
LEFT JOIN creators ON projects.creator_id=creators.creator_id
) t
EOT;
$primaryKey = 'project_id';
$columns = array(
array(
'db' => 'project_id',
'dt' => 'DT_RowId'
),
array(
'db' => 'creator_id',
'dt' => 'creator'
),
array(
'db' => 'creator_name',
'dt' => 'creator_name'
)
);
// SQL server connection information
$sql_details = array(
'user' => '',
'pass' => '',
'db' => '',
'host' => ''
);
require(BASE_DIR.'/lib/dataTables/ssp.class.php');
$result = SSP::simple($_GET, $sql_details, $table, $primaryKey, $columns);
echo json_encode($result);
To use that trick, you also need to edit ssp.class.php and replace all instances of FROM `$table` with FROM $table to remove backticks.
Alternatively, there is github.com/emran/ssp repository for library that extends ssp.class.php allowing GROUP BY, JOIN, aliases.
LINKS
See jQuery DataTables: Using WHERE, JOIN and GROUP BY with ssp.class.php for more information.

Appending one array to another array in the same loop

This is for a custom Wordpress page but I think the basic array principles should apply. I've not worked with complex arrays before so am a little lost, trial and error hasn't worked yet.
I have a database of Posts, each post has meta_key's of 'shop' and 'expired'.
'expired' is a date (YYYY-MM-DD) which is used to tell the visitor when a Post's content expires and this key is what I'm trying to work with.
If a Post's 'expired' date is before today, they are shown 'Offer expired'
If the 'expired' date is in the future, they are shown 'Offer expires in X days' (this script isn't shown below, not necessary)
Posts are listed in order of their 'expired' date, ASC. The problem is that when a post expires I'd like that post to show at the end rather than stay on top.
Example of what I currently see:
Post 1 | Expired 3 days ago
Post 2 | Expired 1 day ago
Post 3 | Expires in 2 days
Post 4 | Expires in 6 days
And what I'd like to see (note Post X order):
Post 3 | Expires in 2 days
Post 4 | Expires in 6 days
Post 2 | Expired 1 day ago
Post 1 | Expired 3 days ago
This is my array code where I've attempted to merge the two
$postid = get_the_ID();
$meta1 = get_post_meta($postid, 'shop', true);
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
$today = date('Y-m-d', time());
$args = array(
'post_type' => 'post',
'meta_query' => array(
array(
'key' => 'shop',
'value' => $meta1
)
),
'paged' => $paged,
'posts_per_page' => '5',
'meta_key' => 'expired',
'meta_value' => $today,
'meta_compare' => '>',
'orderby' => 'meta_value',
'order' => 'ASC'
);
$args2 = array(
'post_type' => 'post',
'meta_query' => array(
array(
'key' => 'shop',
'value' => $meta1
)
),
'meta_key' => 'expired',
'meta_value' => $today,
'meta_compare' => '<',
'orderby' => 'meta_value',
'order' => 'DESC'
);
$final = $args + $args2;
$query = new WP_Query( $final );
while ( $query->have_posts() ) : $query->the_post(); ?>
HTML FOR DISPLAYING POST
endwhile;
At the moment it doesn't seem to take any notice of "$args2" and only displays $args
I'm sure my idea is on the right lines, needing to create two arrays and join them with the "+" rather than array_merge() but that's where I can't get any further.
Can someone kindly shed some light please? Thanks!
Now the solution you are trying to achieve is actually impossible if i understood your requirement properly. Let me explain why this is not achievable.
In your two arrays $args and $args2 most of the values are same leaving two odds , i am picking only one to just illustrate :
//it's in args
'meta_compare' => '>'
//it's in args2
'meta_compare' => '<'
Now what happens when you are trying to merge this two using array_merge($args , $args2):
'meta_compare' => '<'
That means it is taking 'meta_compare' from the later array which is $args2 here. This is the behavior of array_merge function defined in the doc:
If the input arrays have the same string keys, then the later value for that key will overwrite the previous one
Now if you are using + array union operator $args+$args2 :
'meta_compare' => '>'
That means it is taking 'meta_compare' from the first array which is $args here. This is the behavior of + array union operator defined in the doc :
The keys from the first array will be preserved. If an array key exists in both arrays, then the element from the first array will be used and the matching key's element from the second array will be ignored.
Why it is happening because in the same level keys have to be unique . So in your situation they are in the same level :
$args = array ('key' => 'value1')
$args2= array ('key' => 'value2')
So only and only one value can exist here as in the merged array 'key' can point only one.
If this was the scenario :
$args [0] = array ('key' => 'value1' )
$args2 [1]= array ('key' => 'value2' )
Then both of the value stored by key will be resrved. This will be the resulting array :
array(2) {
[0]=>
array(1) {
["key"]=>
string(6) "value1"
}
[1]=>
array(1) {
["key"]=>
string(6) "value2"
}
}
Though i am not a geek of WP but as far as i understood from WP_query you can't pass args like this (I am not sure). So that leaves only one way to achieve this. You can pass these two args separately and merge the result as the result most probably (I am not sure) will be a 2D array you can merge them easily.
Hope that helps.
Happy coding :)
You can't just add 2 arrays together using the args+args2 syntax. PHP has no way of knowing what you mean by that. If you want the result to be an array containing both of these arrays, you could do this:
$final = array($args, $args2)
Otherwise I'm not sure how you want these two arrays combined. If you clarify how they need to be combined we might be able to help more.

Mysql CakePHP 2.0

I want to make a MySQL query in CakePHP 2.0 which looks like this:
select p.ciname HOSTNAME
,a.status HPSA
,m.status SM9
,p.status LDAP
from hpsas a, hpsms m, ldaps p
where (p.ciname = a.ciname)
and (p.ciname = m.ciname)
order by p.ciname;
Is this possible?
You can make arbitrary SQL queries in CakePHP using the Model.query() method. For example, in a controller:
$sql = ...your sql here...
$results = $this->ModelName->query($sql);
if you are trying to make this query using cake ORM I think this would be a step in that direction:
$options = array();
$options['fields'] => array('p.ciname AS HOSTNAME', 'a.status AS HPSA', 'm.status AS SM9', 'p.status AS LDAP');
$options['joins'][] => array('table' => 'hpsas', 'alias' => 'a', 'conditions' => array('p.ciname = a.ciname'));
$options['joins'][] => array('table' => 'hpsms', 'alias' => 'm', 'conditions' => array('p.ciname = m.ciname'));
$result = $this->Test->find('all', $options);
Those fields and table names don't comply with cake convention, understandable if you are migrating or integrating your project. If you are starting now, you might want to rename them.
http://book.cakephp.org/1.3/en/view/901/CakePHP-Conventions

Codeigniter database issue

Having a spot of bother trying to grab some data out of my database.
I have the following model:
function GetRestaurants($options = array())
{
// Qualification
if(isset($options['restaurantID']))
$this->db->where('restaurantID', $options['restaurantID']);
if(isset($options['restaurantRegionID']))
$this->db->where('restaurantRegionID', $options['restaurantRegionID']);
if(isset($options['restaurantName']))
$this->db->where('restaurantName', $options['restaurantName']);
if(isset($options['restaurantAddress1']))
$this->db->where('restaurantAddress1', $options['restaurantAddress1']);
if(isset($options['restaurantAddress2']))
$this->db->where('restaurantAddress2', $options['restaurantAddress2']);
if(isset($options['restaurantSuburb']))
$this->db->where('restaurantSuburb', $options['restaurantSuburb']);
if(isset($options['restaurantCity']))
$this->db->where('restaurantCity', $options['restaurantCity']);
if(isset($options['restaurantInformation']))
$this->db->where('restaurantInformation', $options['restaurantInformation']);
// limit / offset
if(isset($options['limit']) && isset($options['offset']))
$this->db->limit($options['limit'], $options['offset']);
else if(isset($options['limit']))
$this->db->limit($options['limit']);
// sort
if(isset($options['sortBy']) && isset($options['sortDirection']))
$this->db->order_by($options['sortBy'], $options['sortDirection']);
$query = $this->db->get("tblRestaurants");
if(isset($options['count'])) return $query->num_rows();
if(isset($options['restaurantID']))
return $query->row(0);
if(isset($options['limit']) && $options['limit'] == '1')
return $query->row(0);
return $query->result();
}
Now the following code works fine:
$this->load->model('Restaurants_model');
$data['restaurant'] = $this->Restaurants_model->GetRestaurants(array(
'restaurantName' => 'shed 5',
'limit' => '1'
));
However the following does not work:
$this->load->model('Restaurants_model');
$data['restaurant'] = $this->Restaurants_model->GetRestaurants(array(
'restaurantName' => str_replace('-', ' ', $this->uri->segment(2)),
'limit' => '1'
));
Even though the result of
str_replace('-', ' ', $this->uri->segment(2))
is in this instance: ‘shed 5’.
I have compared var_dumps of the output of the str_replace and the string itself and determined them to be identical. So why does the straight string return a result yet the string generated from the uri segment doesn’t? Some kind of encoding issue? My database holds data in ‘utf8_general_ci’.
Thanks for any suggestions!
$restaurant=str_replace('-', ' ', $this->uri->segment(2));
get value outside array and try array_push
$data['restaurant'] = $this->Restaurants_model->GetRestaurants(array(
'restaurantName' => $restaurant,
'limit' => '1'
));