WP_Query not Working if Taxonomy Term has Single Quotes - taxonomy

I'm using WP_Query to retrieve posts based on certain taxonomy terms. The problem is that WP_Query is not returning any results if the term has a single quote.
Here's the relevant portion of the args passed to WP_Query:
[tax_query] => Array
(
[0] => Array
(
[taxonomy] => country
[field] => name
[terms] => Array
(
[0] => People's Republic of China
)
)
)
I tried escaping the quote (e.g. People\'s Republic of China) but still there are no results.
There is no problem with the code as other terms without the quote work. And if you ask, there are posts with the single quotes as validated from directly querying from the database (via phpmyadmin).
I know that I can just query using taxonomy id and slug (e.g. 'field'=>'term_id' AND 'field'=>'slug') but I hope not to as too may code has been written to use the term name.
Thanks

Related

Can I use the andFilterWhere([]) to search for all value that start with?

I am using the yii2 framework and GridView and just learning yii2
Can I use the andFilterWhere([]) to search for all values that start with? a specific value similar to SQL where you can use zip% or is there some function better to use.
I want to search for a zipcode in a database that starts with the the number I entered.
I originally used
->andFilterWhere(['like', 'zip', $this->zip])
but that searches any possible combination.
Yes, you can. It's done like that by passing false as 4th array element:
['like', 'zip', 'zip%', false],
Or if it depends on model attribute value:
['like', 'zip', $this->zip . '%', false],
Please read more about building where section of query here, there is example about this case:
like: operand 1 should be a column or DB expression, and operand 2
be a string or an array representing the values that the column or DB
expression should be like. For example, ['like', 'name', 'tester']
will generate name LIKE '%tester%'. When the value range is given as
an array, multiple LIKE predicates will be generated and concatenated
using AND. For example, ['like', 'name', ['test', 'sample']] will
generate name LIKE '%test%' AND name LIKE '%sample%'. The method
will properly quote the column name and escape special characters in
the values. Sometimes, you may want to add the percentage characters
to the matching value by yourself, you may supply a third operand
false to do so. For example, ['like', 'name', '%tester', false] will
generate name LIKE '%tester'.
Try andFilterWhere as :-
->andFilterWhere(['like', 'zip', $this->zip.'%' ,false]);
it will create query where zip like 'zipcode%'

Rails: Querying with an Array

I have the following method which creates and then executes an SQL query:
def edition_authors(edition, authors)
query_string = "contributor_type = ? AND author = ?"
for i in 1..authors.length - 1
query_string += " OR author = ?"
end
return edition.contributors.where(query_string, 'Author', authors)
end
The last line is the one I'm having trouble with. I want the 'authors' array to somehow turn into a set of strings. For instance, if the authors array contained ['James Joyce', 'Cory Doctorow', 'Cormac McCarthy'], I'd like that last line to read like:
return edition.contributors.where(query_string, 'Author', 'James Joyce', 'Cory Doctorow', 'Cormac McCarthy')
How could I accomplish this?
Depends which rails and which ruby you are using,
ActiveRecord already has this functionality in Rails 3: Model.where(:my_field => ['Author', 'James Joyce', 'Cory Doctorow', 'Cormac McCarthy'])
arr.map{|v| v.to_s.inspect} will get you a comma separated list
arr.join(',') will give you a comma separated list, no quotes.
Then you can use this string however you wish.
Try this:
Instead of using a big bunch of ORs, use a SQL IN clause, and
then use Array#join to supply the values
So:
.where("contributor_type = ? AND author IN (?)", 'Author', authors.join("','"))
should do the trick, with some caveats: string values in a SQL IN clause need to be single quoted and comma separated SELECT * FROM fubar WHERE blah IN ('foo','bar','baz'); I think Rails is clever about knowing how to quote things, so look in the Rails log to see what SQL is being generated if you're getting an error.
Also, since your values may contain single quotes (Georgia O'Keefe) I am not sure if Rails is smart enough to escape these for you when used in this manner.
Bonus tip: make sure there's an index on the Author column. This is an expensive query, in general.

Sorting strings with numbers and text in Rails

In my database I have table with a name column containing grades, like 1. grade, 2. grade, and so on. When the numbers have reached 10 or more, the sorting doesn't work as I would like, as 10. grade comes before 2. grade in the sorted recordset. I know this is because string sorting is different from integer sorting. The question is how to sort these strings in a numeric way.
Because the grade-records are a part of a tree buildt with the ancestry plugin, I have to put the whole sorting code inside :order => "(some code that sorts the results)".
I have tried :order => "CAST(SUBSTRING_INDEX(name, '.') AS SIGNED)". But this doesn't work.
I use SQLite in my development environment and MySQL in the production environment.
try this:
replace the constant vale '. grade' of your column with empty string, then you get the numeric value. cast the same to int
order by cast(replace(name,'. grade','') as int)
EDIT:
as per your comment if its not 'grade' always, then try
order by cast(left(name,LOCATE('.',name,1)-1) as UNSIGNED)
SQL fiddle demo

Search in mysql database - unserialized data

Situation:
I have user model. attribute "meta_data" in db represents "text" type field.
In model it seriazized by custom class. ( serialize :meta_data, CustomJsonSerializer.new )
It means, when I have an instance of user, I can work with meta_data like with Hash.
User.first.meta_data['username']
Problem:
I need to write a search function, which will search users by given string. I can do it by manual building search query in rails ex. User.where("email LIKE '%#{string}%'")...
But what about meta_data ? Should I search in this field by LIKE statement too? If I will do so, it will decrease relevance of found record.
For example:
I have 2 users. One of them has username "patrick", another one is "sergio"
meta data in db will look like this:
1) {username: patrick}
2) {username: sergio}
I want to find sergio , I enter a search string "ser" => but I have 2 results, instead of one. This meta_data string "{uSERname: Patrick}" also has "ser", so it makes this record irrelevant.
Do you have any idea how to solve it?
That's really the problem with serialized data. In theory, the serialization could be an algorithm that is very unsearchable. It could do a Hoffman encoding, or other compression, and store the serialization in binary. You are relying on the assumption that the serialization uses JSON and your string will still be findable as a sub-string in the serialization.
Then the problem you are having is another issue. Other data in the serialization can mess up your results.
In general, if you serialize data, you are making a choice to not be searchable.
So a solution would be to add an additional field that you populate in a way that you control. Have a values field and store a pipe (|) delimited value that you can search. So if the data is {firstname: "Patrick", lastname: "Stern"}, your meta_values field might be "Patrick|Stern".
Also, don't use the where method with a string with #{} expansion of input values. The makes it vulnerable to SQL attacks. Instead use:
where("meta_values is like :pattern", pattern: "%#{string}%")
I know that may not look very different, but ActiveRecord will go through a sanitizing this way. If someone has a semi-colon in string, then ActiveRecord will escape the semi-colon in the search condition.

Django: Use variable names instead of %s

Im passing multiple parameter into a raw sql statement, for each parameter im using %s
Is it possible to use the variable name instead of multiple %s
Example:
man = "John"
wife = "Jane"
query = "SELECT * FROM person WHERE name = %s and wife = %s"
cursor.execute(query, [man, wife])
Is it a model you are querying?
Looking at the docs explaining the raw() manager
raw() automatically maps fields in the query to fields on the model.
this should be as easy as:
Person.objects.raw('SELECT id, first_name, last_name, birth_date FROM myapp_person')
DB API 2.0 defines following parameter styles
'qmark' Question mark style,
e.g. '...WHERE name=?'
'numeric' Numeric, positional style,
e.g. '...WHERE name=:1'
'named' Named style,
e.g. '...WHERE name=:name'
'format' ANSI C printf format codes,
e.g. '...WHERE name=%s'
'pyformat' Python extended format codes,
e.g. '...WHERE name=%(name)s'
Now, not all databases implement all of them. Check if DB engine you're using does support pyformat.