Removal of capitals and spaces in opencart - php

I'm creating a module in Opencart and have used the standard 'model' to add an array into the database. Unfortunately when I retrieve via
$this->data['font'] = unserialize($this->config->get('selectfont'));
The information has removed the capital letters and spaces between the words. How can I add the capitals and spaces back into the variables? Sorry been racking my brains over this for days. Help much appreciated.
Davetoff
Ok so I've done some digging around in the back and basically the POST command puts the data into the database via serialize:
if (($this->request->server['REQUEST_METHOD'] == 'POST') && $this->validate()) {
foreach ($this->request->post as $key => $value) {
$this->request->post[$key] = serialize($value);
}
So when I retrieve it via:
$this->data['font'] = unserialize($this->config->get('selectfont'));
it should work but doesn't. I've attached a line of the sort of data field I have in the data base:
a:6:{i:0;s:11:"segoescript";i:1;s:5:"serif";i:2;s...etc etc
This should unserialize...right?
Help please.

UPDATE tbl_url_alias SET keyword = LOWER(keyword)
UPDATE tbl_url_alias SET keyword = REPLACE (keyword, ' ', '-')
Run this query in the database, for which table you needed.

Related

PHP search MySQL

I've got this code:
function searchMovie($query)
{
$this->db->where("film_name LIKE '%$query%'");
$movies = $this->db->get ("films", 40);
if($this->db->count > 0)
{
return $movies;
}
return false;
}
Javascript code from my submit form button strips all special characters like ; : ' / etc. from query string, and then redirects user to search uri (szukaj/query). So for example if film_name is Raj: wiara, and user searches for raj: wiara, the query looks like raj wiara and user doesn't get any results. I was thinking about exploding query into single words and then foreach word do a SELECT from db, but it would give multiple results of same movie. Don't want to change the javascript code, and I think I can't make that film names without the special characters like :.
Or maybe create another column in db for film_keywords and add there all words of movie separated by , or something and then search this column?
MySQL's Full Text Search functions are your friend here:
http://dev.mysql.com/doc/refman/5.7/en/fulltext-search.html
Will return a series of matches and give a score so you return in best-match order.
Warning: $this->db->where("film_name LIKE '%$query%'"); is open to SQL injection. Anyone can circumnavigate the JavaScript so you must always clean up input server-side. This is best done using the DB functions as well, not just stripping characters - so check whatever library you are using in order to do this.
You could indeed explode your string, using this answer's solution.
function searchMovie($query)
{
$queries = preg_split('/[^a-z0-9.\']+/i', $query);
foreach ($queries as $keyword){
$this->db->where("film_name LIKE '%$keyword%'");
}
$movies = $this->db->get ("films", 40);
if($this->db->count > 0)
{
return $movies;
}
return false;
}
This will create multiple ANDconditions for your db where, so the result will be filtered.

How to find #hashtags in strings using Laravel 4.1?

I am currently trying to filter through an Input string to find the single hashtags that a user wants to be displayed with his photo. However, I am currently getting inserts in my database that are not correct.
The best case scenario would be that every single hashtag is saved in a new database row with the photo id. However, I do not really know what to do to accomplish that.
$hashtag = new Hashtag;
$hashtag->photo_id = $photo->id;
$hashtag_string = Input::get('hashtags');
$hashtag_string = Str::contains($hashtag_string, '#')
$hashtag->hashtag = $hashtag_string;
$hashtag->save();
I found some functions in this cheat sheet (http://cheats.jesse-obrien.ca) but I do not get them to work properly.
Try this:
$str = $hashtag_string;
preg_match_all('/#(\w+)/', $str, $matches);
foreach ($matches[1] as $hashtag_name) {
$hashtag = Hashtag::firstOrCreate(array('hashtag' => $hashtag_name));
}
You could then, in this foreach loop, connect those hashtags to a post (or in your case a photo) or sth.

Add/Replace URL GET parameter depending on current URL

I’ve tried for some time now to solve what probably is a small issue but I just can’t seem get my head around it. I’ve tried some different approaches, some found at SO but none has worked yet.
The problem consists of this:
I’ve a show-room page where I show some cloth. On each single item of cloth there is four “views”
Male
Female
Front
Back
Now, the users can filter this by either viewing the male or female model but they can also filter by viewing front or back of both gender.
I’ve created my script so it detects the URL query and display the correct data but my problem is to “build” the URL correctly.
When firstly enter the page, the four links is like this:
example.com?gender=male
example.com?gender=female
example.com?site=front
example.com?site=back
This work because it’s the “default” view (the default view is set to gender=male && site=front) in the model.
But if I choose to view ?gender=female the users should be able to filter it once more by adding &site=back so the complete URL would be: example.com?gender=female&site=back
And if I then press the link to see gender=male it should still keep the URL parameter &site=back.
What I’ve achived so far is to append the parameters to the existing URL but this result in URL strings like: example.com?gender=male&site=front&gender=female and so on…
I’ve tried but to use the parse_url function, the http_build_query($parms) method and to make my “own” function that checks for existing parameters but it does not work.
My latest try was this:
_setURL(‘http://example.com?gender=male’, ‘site’, ‘back’);
function _setURL($url, $key, $value) {
$separator = (parse_url($url, PHP_URL_QUERY) == NULL) ? '?' : '&';
$query = $key."=".$value;
$url .= $separator . $query;
var_dump($url); exit;
}
This function works unless the $_GET parameter already exists and thus should be replaced and not added.
I’m not sure if there is some “best practice” to solve this and as I said I’ve looked at a lot of answers on SO but none which was spot on my issue.
I hope I’ve explained myself otherwise please let me know and I’ll elaborate.
Any help or advice would be appreciated
You can generate the links dynamically using the following method:
$frontLink = (isset($_GET['gender'])) ? 'mydomain.com?gender='.$_GET['gender'].'&site=front':'mydomain.com?site=front';
$backLink = (isset($_GET['gender'])) ? 'mydomain.com?gender='.$_GET['gender'].'&site=back':'mydomain.com?site=back';
This is a 1 line if statement which will set the value of the variables $frontLink and $backlink respectively. The syntax for a 1 line if statement is $var = (if_statement) ? true_result:false_result; this will set the value of $var to the true_result or false_result depending on the return value of the if statement.
You can then do the same for the genders:
$maleLink = (isset($_GET['site'])) ? 'mydomain.com?gender=male&site='.$_GET['site']:'mydomain.com?gender=male';
$femaleLink = (isset($_GET['site'])) ? 'mydomain.com?gender=female&site='.$_GET['site']:'mydomain.com?gender=female';
Found this by searching for a better solution then mine and found this ugly one (That we see a lot on the web), so here is my solution :
function add_get_parameter($arg, $value)
{
$_GET[$arg] = $value;
return "?" . http_build_query($_GET);
}
<?php
function requestUriAddGetParams(array $params)
{
$parseRes=parse_url($_REQUEST['REQUEST_URI']);
$params=array_merge($_GET, $params);
return $parseRes['path'].'?'.http_build_query($params);
}
?>
if(isset($_GET['diagid']) && $_GET['diagid']!='') {
$repParam = "&diagid=".$_GET['diagid'];
$params = str_replace($repParam, "", $_SERVER['REQUEST_URI']);
$url = "http://".$_SERVER['HTTP_HOST'].$params."&diagid=".$ID;
}
else $url = "http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']."&diagid=".$ID;

Is this the right way to use Sphinx from PHP?

I am just starting with Sphinx. So far I got it installed successfully, got a table called profiles on my MySQL database indexed and am able to get the correct results back using the PHP API. I am using CodeIgniter so I wrapped the default PHP API as a CodeIgniter library.
Anyway this is how my code looks like:
$query = $_GET['q'];
$this->load->library('sphinxclient');
$this->sphinxclient->setMatchMode(SPH_MATCH_ANY);
$result = $this->sphinxclient->query($query);
$to_fetch = array();
foreach($result['matches'] as $key => $match) {
array_push($to_fetch, $key);
}
The array $to_fetch contains the ids of the matched table rows. Now I can use a typical MySQL query to get all the relevant users to display on the search page like so:
$query = 'SELECT * FROM profiles WHERE id IN('. join(',', $to_fetch) . ')';
My question are:
is this the right way to go about it? or is there a default "Sphinx way of doing it" that would be better for performance .
secondly, all I get back at the moment is the id of the matched table rows. I also want the part of the text in the column that matched. For example if a someone searches for the keyword dog and a user on the profiles table had in their about column the following text:
I like dogs. I also like ice cream.
I would like Sphinx to return:
I like <strong>dogs</strong>. I also like ice cream.
How can I do that? I tried to play around with the buildExcerpts() function but can't get it to work.
EDIT
This is how I am getting excerpts now:
// get matched user ids
$to_fetch = array();
foreach($result['matches'] as $key => $match) {
array_push($to_fetch, $key);
}
// get user details of matched ids
$members = $this->search_m->get_users_by_id($to_fetch);
// build excerpts
$excerpts = array();
foreach($members as $member) {
$fields = array(
$member['about'],
$member['likes'],
$member['dislikes'],
$member['occupation']
);
$options = array(
'before_match' => '<strong class="match">',
'after_match' => '</strong>',
'chunk_separator' => ' ... ',
'limit' => 60,
'around' => 3,
);
$excerpt_result = $this->sphinxclient->BuildExcerpts($fields, 'profiles', $query, $options);
$excerpts[$member['user_id']] = $excerpt_result;
}
$excerpts_to_return = array();
foreach($excerpts as $key => $excerpt) {
foreach($excerpt as $v) {
if(strpos($v, '<strong class="match">') !== false) {
$excerpts_to_return[$key] = $v;
}
}
}
As you can see I am searching each query across 4 different mysql columns:
about
likes
dislikes
occupation
Because of this I don't know which of the 4 columns contains the matched keyword. It could be any of them or even more than one. So I have no choice but to run the contents of all 4 columns through the BuildExcerpts() function.
Even then I don't know which one the BuildExcerpts() returned with the <strong class="match"> tags. So I run a stpos check on all values returned by BuildExcerpts() to finally get the proper excerpt and map it to the user whose profile it belongs to.
Do you see a better way than this given my situation where I need to match against the contents of 4 different columns?
Yes that looks good way. One thing to remember the rows coming back from Mysql probably won't be in the order from sphinx.
See the FAQ on sphinx site for how to use FIELD() but personally I like to put the rows from sphinx into associative array, then just loop though the sphinx I'd list and get the row from the array. Avoids a sorting phase altogether at the expense of memory!
As for highlighting, yes do persevere with buildExcerpts - that's is the way to do it.
edit to add, this demo
http://nearby.org.uk/sphinx/search-example5-withcomments.phps
demonstrates both getting rows from mysql and "sorting" in the app. And buildExcerpts.

MODX parse error function implode (is it me or modx?)

Update 4-June-2010: This appears to be a bug in MODx v 1.0.3, nothing to do with the implode function but rather a problem with mis-matched datatypes in the resulting filter clause. Bug has been filed with JIRA: MODX-2035.
Hi, I cannot for the life of me figure this out, maybe someone can help.
Using MODX a form takes user criteria to create a filter and return a list of documents. The form is one text field and a few checkboxes. If both text field and checkbox data is posted, the function works fine; if just the checkbox data is posted the function works fine; but if just the text field data is posted, modx gives me the following error:
Error: implode() [function.implode]: Invalid arguments passed.
I've tested this outside of modx with flat files and it all works fine leading me to assume a bug exists within modx. But I'm not convinced. Here's my code:
<?php
$order = array('price ASC'); //default sort order
if(!empty($_POST['tour_finder_duration'])){ //duration submitted
$days = htmlentities($_POST['tour_finder_duration']); //clean up post
array_unshift($order,"duration DESC"); //add duration sort before default
$filter[] = 'duration,'.$days.',4'; //add duration to filter[] (field,criterion,mode)
$criteria[] = 'Number of days: <strong>'.$days.'</strong>'; //displayed on results page
}
if(!empty($_POST['tour_finder_dests'])){ //destination/s submitted
$dests = $_POST['tour_finder_dests'];
foreach($dests as $value){ //iterate through dests array
$filter[] = 'searchDests,'.htmlentities($value).',7'; //add dests to filter[]
$params['docid'] = $value;
$params['field'] = 'pagetitle';
$pagetitle = $modx->runSnippet('GetField',$params);
$dests_array[] = ''.$pagetitle.'';
}
$dests_array = implode(', ',$dests_array);
$criteria[] = 'Destinations: '.$dests_array; //displayed on results page
}
if(is_array($filter)){
$filter = implode('|',$filter);//pipe-separated string
}
if(is_array($order)){
$order = implode(',',$order);//comma-separated string
}
if(is_array($criteria)){
$criteria = implode('<br />',$criteria);
}
echo '<br />Order: '.$order.'<br /> Filter: '.$filter.'<br /> Criteria: '.$criteria;
//next: extract docs using $filter and $order, display user's criteria using $criteria...
?>
The echo statement is displayed above the MODX error message and the $filter array is correctly imploded.
Any help will save my computer from flying out the window.
Thanks
I think your problem lies here :
$dests_array = implode(', ',$dests_array);
$dest_array may be empty and not even initialized if $dests is empty.
This really should be posted in the MODx forums. I love stackoverflow, but MODx is more niche.

Categories