Search LIKE json object in mysql - php

Suppose in my sample_table exist field json_field (stringified JSON object, has property_1, property_2)
How can i select like this request: WHERE property_1 LIKE %VALUE_1% AND property_2 LIKE %VALUE_2% without fetching all data and search with php?
P.S. Yes i know, that was mistake to keep json string in field

You can't.
If you want to get data in your script you have to fetch them. Building dynamic request with the arguments.
Something like :
"...WHERE property_1 LIKE '".$value_1."' AND property_2 LIKE '".$value_2.'";

Not familiar with php, however a decent database interface should allow u to execute any select statement. So according to https://dev.mysql.com/doc/refman/8.0/en/create-table-secondary-indexes.html#json-column-indirect-index you should be able to query based on properties inside a JSON type column.
Even using where col->"$.propertyName" = xxx would work.
Using like 'xxx%' prefix search doesn't seem to work correctly though.
But with the page linked above. You should be able to create a generated column on frequently searched field and create index based on it and search like regular column.

basically JSON_EXTRACT() + LIKE + quote() (if you're using PDO) or real_escape_string() (if you're using mysqli)
$db->query("SELECT * FROM sample_table WHERE
JSON_EXTRACT(`json_field`, '$.property_1') LIKE "
. $db->quote("%{$VALUE_1}%").
" AND JSON_EXTRACT(`json_field`, '$.property_2') LIKE "
. $db->quote("%{$VALUE_2}%")

Related

Query in PHP with 'and' or 'or' as variable

I would like to do search for advanced search. The Search feature has and/or for every category. User can choose any combination of and n or. Here i give the screenshot
I store the and/or into variable call $pil, $pil1,$pil2 and $pil3. And will put them in query. it's better than validate one by one every condition of and/or
So this is my query using postgresql in PHP
$query = pg_query("SELECT evaluationdate,onlinename,channel,topik,reviewername,sourceevaluation,evaluation
from AgentPerformance
where onlinename like '%".$VEOn1."%'
".$pil." reviewername like '%".$VERev1."%'
".$pil1." channel like '%".$VEChan1."%'
".$pil2."sourceevaluation like '%".$VESource1."%'
".$pil3."evaluationdate between '".$VEStart1."' and '".$VEEnd1."'");
EDIT :
The problem now, All the variables must not be empty or the query will be error. any way to trick this?
You've missed some spaces near sourceevaluation and evaluationdate
Try with this query :
$query = pg_query("SELECT evaluationdate,onlinename,channel,topik,reviewername,sourceevaluation,evaluation
from AgentPerformance
where onlinename like '%".$VEOn1."%'
".$pil." reviewername like '%".$VERev1."%'
".$pil1." channel like '%".$VEChan1."%'
".$pil2." sourceevaluation like '%".$VESource1."%'
".$pil3." evaluationdate between '".$VEStart1."' and '".$VEEnd1."'");
Simply. Use validation for each $pil whether it is empty or not. it makes me validate 4 times, but it solves the problem. The syntax error has been solved too

Mysql query keyword changes to unknown character set in php in case of Mobile devices

I am using a search query for selecting names in my DB by giving a keyword.
My query is
SELECT `engine4_core_search`.* FROM `engine4_core_search` WHERE ((`engine4_core_search`.`title` LIKE "%".$text."%"))
When give " cardiff " (cardiff comes in place of $text ) as my keyword and checking the query ..it displays like
SELECT `engine4_core_search`.* FROM `engine4_core_search` WHERE ((`engine4_core_search`.`title` LIKE 'Êrdiff%'))
Is there any method to solve this.
Thanks in advance.
It seems to be you have included jQuery-mobile (because tagged in it)
In some cases jQuery-mobile replaces some strings when they attached with different patterns like " %cardiff " . It may considers to be different string set
Just remove jQuery-mobile and try for your output......

Retrieve json data from array using select

Lets say I have this info stored in my database, in a JSON format.
ROW with id=23: {
"age":50,
"name":"Nick",
"messages":["msg 1","msg 2","msg 3"]
}
ROW with id=24: {
"age":22,
"name":"John",
"messages":["msg 4","msg 3","msg 9"]
}
Now, all I want is to perform an SQL query using PHP to retrieve rows that contains the message msg 3.
How can I do that?
Any advice will be appreciated.
Thanks
Using LIKE '%%' is performance overkill, try to avoid that.
Objects are made to live, why fossilize them ?
Not to mention, this is also obviously violating 1NF.
As someone suggested, why don't you try MongoDB or other NoSQL database ? Queries are performed using JSON (well, BSON...)

LIKE Condition in PHP Not Work correctly

i have a row in my database with name "active_sizes" and i want filter my website items by size, for this, i use LIKE Condition in php :
AND active_sizes LIKE '%" . $_GET['size'] . "%'
but by using this code i have problem
for example when $_GET['size']=7.0 this code shows items that active_sizes=17.0
my active_sizes value looks like 17.0,5.0,6.5,7.5,,
thanks
Using comma-separated values in a single field in a database is indicative of bad design. You should normalize things, and have a seperate "item_sizes" table. As it stands now, you need a VERY ugly where clause to handle such sub-string mismatches:
$s = (intval)$_GET['size'];
... WHERE (active_sizes = $s) // the only value in the field
OR (active_sizes LIKE '$s%,') // at the beginning of the field
OR (active_sizes LIKE '%,$s,%') // in the middle of the field
OR (active_sizes LIKE '%,$s') // at the end of the field
Or, if you normalized things properly and had these individual values in their own child table:
WHERE (active_sizes_child.size = $s)
I know which one I'd choose to go with...
You don't state which DB you're using, but if you're in MySQL, you can temporarily accomplish the same thing with
WHERE find_in_set($s, active_sizes)
at the cost of losing portability. Relevant docs here: http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_find-in-set
You Have % signs around your $_GET value. Combined with LIKE, this means that any string that simply contains your get value will be retuned. If you want an exact match, use the = operator instead, without the percentage signs.
This will solve your immediate issue:
AND active_sizes LIKE '" . mysql_real_escape_string($_GET['size']) . "%'
If you are using the database other than MySQL, use corresponding escape function. Never trust input data.
Besides, I'd suggest using numeric field (DECIMAL or NUMERIC) for active_sizes field. This will accelerate your queries, will let you consume less memory, create queries like active_sizes BETWEEN 16.5 AND 17.5, and generally this is more correct data type for a shoe size.

what's the most easy-to-parse format for PHP?

In my PHP file,I'm reading out bulk of information using query like below:
SELECT GROUP_CONCAT(CONCAT('<comment><body><![CDATA[',body,']]></body>','<replier>',if(screen_name is not null and !anonymous,screen_name,''),'</replier>','<created>',created,'</created></comment>') SEPARATOR '')
FROM idiscussion
LEFT JOIN
users
ON idiscussion.uid=users.id
WHERE idiscussion.iask_id = 1
yes,it's like xml format,but seems it's not easiest to parse in PHP,
Any recommendation on which format to use in order to parse easily later on?
AS for my I need to concatenating them all together,
You can think about this case: To retrieve 1 topic and discussions under this topic at a time. 1 topic corresponds to multiple discussions.How can you do it in 1 query without concatenating it together?
If you're getting data from a SQL database, it's much easier not to use SQL to clobber it into some text format, but to instead perform a regular query and use the SQL functions to work with the results that you're given.
If you end up needing to serialize data to other PHP clients, I would recommend PHP's standard serialization format.
Depends on the data structure, but a list of values may easily be saved as a semi-colon separated list of entries using join(), and then easily parsed using split().
This is extremely simple, but may not be ideal for slightly more complex data.
Answer to comment: if the data contains a semi-colon, it needs to be escaped as appropriate.
You could use DOM or SimpleXML to parse XML files, but also JSON or YAML. All are quite easy to use as you can rely on high-level parsers for PHP. They have advantages and disadvantages depending on how you want to use the format.
Can I ask why you're not just retrieving the data without concatenating it all together?
SELECT body,
IF(screen_name IS NOT NULL AND !anonymous, screen_name, '') AS replier,
created
FROM idiscussion
LEFT JOIN
users
ON idiscussion.uid = users.id
WHERE idiscussion.iask_id = 1
This should execute as quickly as your original query, and you can access its data as you would any other result set. Assuming you're using MySQL and not using PDO:
$result = mysql_query($sql);
if ($result) {
while ($row = mysql_fetch_assoc($result)) {
// $row is an associative array containing the current row's data.
}
}
If you need to create the XML but also want to access the data in its raw form, just create it in the PHP.
$xml =
'<comment>' .
'<body><![CDATA[' . $row['body'] . ']]></body>' .
'<replier>' . $row['replier'] . '</replier>' .
'<created>' . $row['created'] . '</created>' .
'</comment>';
You may need to escape the data if it hasn't been sanitised already. You could also use an XML builder such as XMLWriter, though that's beyond the scope of this question.

Categories