Get json store data from database in codeigniter - php

I was storing Json data in Php database like this ["4","2"]. Problem is that i want to get data from json id using where clause . Is there any solution for that?
I was also use this JSON_CONTAINS but not working.
SELECT membermaster.* FROM membermaster WHERE membermaster.status = 'Active' AND membermaster.role = 'client' AND JSON_CONTAINS(client_type,"2")
Sorry for my bad english. Thank You.

Can you tell which Mysql version you are using because JSON_CONTAINS only will work in greater than equal MySql 5.7 version? It also depends on the server setting and database open extension settings.
If you want to get data using the where clause you can write a query like below.
SELECT membermaster FROM membermaster WHERE membermaster.status = 'Active' AND membermaster.role = 'client' AND client_type like '%"2"%';
Or if you want you can use regex also.

Related

Not able to use JSON_EXTRAXT in mysql

I am using XAMPP for Linux 5.6.30 and MySQL version is 10.1.21-MariaDB
I have one table 'employee'
id data
1 [{"name":"abc","age":"56","dob":"2017-05-15","about":"test"}]
2 [{"name":"xyz","age":"26","dob":"2017-09-20","about":"test"}]
3 [{"name":"pqr","age":"96","dob":"2017-03-05","about":"test"}]
Table field data contains JSON string.
I want to find name from JSON and my query efforts is
SELECT * FROM `tbl_employee` WHERE JSON_EXTRACT(data,"$.name") = "abc"
SELECT * FROM `tbl_employee` WHERE data->"$.name" = "abc"
but it gives me an error
> #1305 - FUNCTION testing.json_extract does not exist
I take reference from this link
Please give me suggestions regarding this?
Is my database not able to do that OR I have used wrongly?
The function JSON_EXTRACT in maria db is available since version 10.2.3,
you can read the documentation here.
You have to update your maria db installation to use that function.
I think, the version you are using it is not exist for your case (JSON_EXTRACT). If you are work on php, you can use php native function json_decode().
Further can be found here : Error code 1305

How to write MySQL Query in Laravel 5 without using PHP String function?

I need to eliminate the specific prefix of a string by default on getting value from the database.
In MySQL, i can use the following,
SELECT RIGHT('abc3',1) -- Results in "3"
SELECT RIGHT('abc3',2) -- Results in "c3"
But, how can i use same process in Laravel eloquent?.
Or any other solutions are available for remove the prefix of a string while retrieve from database in laravel.
I know trim will eliminate, but only spaces.
ex.
property_color
property_size
Here i need to extract "property_".
expect.
color
size
Is it possible in laravel, in without using PHP String function.
Only on Direct eloquent Operation.
Thanks in Advance !
That's what I would do:
$arrayData = DB::select(DB::raw("SELECT RIGHT('abc3',1) ")):
you can pass array of parameter to bind values:
DB::select(DB::raw(" SQL QUERY "),$paramsArray);
You have to use raw queries within your builder like
$results = YourRepo::where(DB::raw("SELECT SUBSTRING('property_color',9)") , 'LIKE', "%property_xxx%");
keep in mind that substring is slow.

ORDER BY on MySQL stored function in CakePHP 3

I'm working on cakePHP 3. I have a user defined function(UDF or Routine) in mysql database. That function takes a parameter and returns an integer value. I have to order that returned value in MySQL order clause.
I know mysql query to use that function. i.e,
SELECT customer_id FROM table_name ORDER BY routine_name(param1); //param1 is 'customer_id' which I have written after SELECT
But I don't know that how to build this query in cakePHP 3. If anyone knows the solution, answer will be appreciate.
Here is my cakePHP 3 code.
$purchasesTable = TableRegistry::get("Purchases");
$query = $purchasesTable->find();
$sf_val = $query->func()->routine_name(['Purchases.customer_id' => 'literal']);
$query->select();
$query->order(
// Routine/Function call should be here as per MySQL query.
// So, I think here I have to do something.
);
I'd suggest that you have a closer look at the (API) docs, it's all mentioned there. You can pass expression objects to Query::order(), and in case you need to specify the direction, there's also Query::orderAsc() and Query::orderDesc().
So
$expression = $query->func()->routine_name(['Purchases.customer_id' => 'literal']);
$query->order($expression);
or
$query->orderAsc($expression);
or
$query->orderDesc($expression);
See also
Cookbook > Database Access & ORM > Query Builder > Selecting Data
API > \Cake\Database\Query::order()
API > \Cake\Database\Query::orderAsc()
API > \Cake\Database\Query::orderDesc()

Is it possible to hide the real column name from a table during json_encode time?

I am encoding a php array into json format which have data from a table.
My json_encode produces result with real column name of that table.I want to use the real column name in php side and after it encode to json format I will like to use some other custom name so, that if some user checks in .js file it won't be any problem for me.Below code is the result of json_encode.
What is now :-
{"result":[{"pals_id":"20","from_user":"hancy061","to_user":"hari061","username":"hancy061"}
What I want :-
{"result":[{"pid":"20","fu":"hancy061","tu":"hari061","un":"hancy061"}
Ya, there isn't any need to show user column name and it seems unsecure too.You guys can see what i want have the json_encode format which I want it to be.Is it possible from php side?I mean in php side before encoding the array into json format can we first make custom name of those columns?
You cannot safely replace these columns on the client-side, because it will be available to a user somehow. If you want a user to never learn how your columns are actually named, you should do this at the server-side.
The most common way is to use SQL aliases.
In your PHP change your SQL query to the following:
SELECT pals_id AS pid, from_user AS fu, to_user AS tu, username AS un FROM YourTable ...
However, that's a security through obscurity and doesn't provide any safety.
If you have an SQL-injection vulnerability, then a hacker will be able to query your data structure from system tables or simply SELECT *.
You could also manually set the array keys in the format you want before encoding, like:
foreach ($result as $ind => $r) {
$result[$ind] = [ // For PHP Versions < 5.4 use 'array('
"pid" => $r['pals_id'],
"fu" => $r['from_user'],
"tu" => $r['to_user'],
"un" => $r['username'],
]; // For PHP Version < 5.4 use ');'
}
However you would then have to reverse this if data were to be sent back to the server from the client for updates or something.
If that is needed, then you could set up a map to switch between the two.

Search LIKE json object in mysql

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}%")

Categories