How to retrieve data from json column using codeigniter? - mysql

I’m a beginner with codeigniter. I’m trying to retrieve data from json column of my sql db
The db structure is like this
DB NAME : order
——————————————————------------------------------------------
Id | description
——————————————————————————————————---------------------------
1 | {“pc”: [{ “brand”: “name”}], “mouse”: [“LL”, “DC”]}
————————————————————————————————————--------------------------
For example, I want to retrieve all instances that has mouse = dc
$data = $this->db->select($select)->from(‘order’)
->where(“mouse”, “DC”) ->get()->result();

Well, I've never worked like this before, but with the help of the user ascsoftw answer, I've found this section on the MySQL documentation that might help, I think this is even better for you case.
Then, your query may look something like this (sorry if I'm mistaken, like I said, never worked like this before):
SELECT Id FROM order where description->>"$[1][1]";
From what I understand that would retrieve all the Id's of the mouse (array index 1) with DC's description (array index 1 as well).
You may keep reading the docs of MySQL if that didn't help.
By the way,is worth mention that, you have several ways to do queries in CodeIgniter, if the CI query builders does not adapt to what you want to do, you can always do as the following example:
$query = "SELECT * FROM table_name";
$result = $this->db->query($query);
if($result->num_rows() != 0)
{
foreach($result->result() as $row)
{
return something
}
}
else
{
return false
}
Let me know if that helped you so I can edit with the correct answer for anyone running into the same problem.

Related

Which is faster for checking, sql/database query or file_get_content?

I have this type of data which i call ids
I have 8.6M of these ids which i use for "validity" check.
tt9916820
tt9916822
tt9916824
tt9916826
I was wondering which would be better & faster?
Using file_get_contents() like this:
$imdbid = $_GET['id'];
if (strpos(file_get_contents("http://127.0.0.1/ids.txt"),$imdbid) !== false) {
echo 'valid id';
} else {
echo 'invalid id';
}
or if i should just import all the 8.6M+ ids to my database and use sql query like this:
$imdbid = $_GET['id'];
$existing = $wpdb->get_var("SELECT COUNT(*) from wp_postmeta where dbids='$imdbid'");
if ($existing) {
echo 'valid id';
} else {
echo 'invalid id';
}
Which one would be faster?
Im newbie, if there are any and any better ways of doing this, please let me know as i wanted to learn more. Thank you!
With a suitable INDEX, the database can discover whether a given value is in the table, and do it in a few milliseconds.
Searching a file with 8.6 million rows (perhaps 86MB in your example) will seconds, maybe even minutes. Furthermore, your suggested code will need room to hold that entire 86MB between fetching and searching.
And, with strpos, if the ids are variable length, you could get a spurious match. For example, searching for "tt9916822" will get 3 hits, none of which are successful. The database solution will prevent this.
tt9916824
tt9916826
tt99168220
tt99168221
tt99168222
If the file does not change often then you should import it into a table and create an index on the column you want to search on. A query on an indexed column should be much faster than:
fetching an 8MB (86MB?) file over the wire
loading all of it into memory (php has a memory limit)
searching it using strpos (which only stops if it finds a match or reaches the end of string)
only to find that the value being searched does not exist

get sql query from collection model

I know that we can get sql query from magento model collection using this,
getSelect();
But I can get query from only the model collections, not worked in others or May be I dont know how to use it.
Here I want to know what query is running behind this,
$productModel = Mage::getModel('catalog/product')->getCollection();
$attr = $productModel->getResource()->getAttribute("color");
if ($attr->usesSource()) {
echo $color_label = $attr->getSource()->getOptionText("28");
}
If I use this,
echo $productModel->getSelect(); exit;
I'm just get the one part the query only, like,
SELECT `e`.* FROM `catalog_product_entity` AS `e`
Update:
This is my full code,
<?php
require_once('app/Mage.php'); //Path to Magento
umask(0);
Mage::app();
$productModel = Mage::getModel('catalog/product')->getCollection();
$attr = $productModel->getResource()->getAttribute("color");
if ($attr->usesSource()) {
$color_label = $attr->getSource()->getOptionText("28");
}
$productModel->printlogquery(true);exit;
Please help me guys,
Your order condition is not visible in the query. The reason your order isn't showing is because the orders are added to the query during the load() method.
See Varien_Data_Collection_Db::load()
Try calling load(true) to see the complete SQL containing the order by clause.
$productModel->load(true);
$productModel->printLogQuery(true);
Hope it helps.
If you want to see what is the exact query, then you can get this by using:
$productModel->printlogquery(true);exit;
Use this code after you have loaded your model's object and applied all conditions.
I hope this will help you.
Magento collecting data with lot of internal queries - models and lot of checks, and may be more than 1 table. So it is not possible to get the query like what I'm looking for.

Query on custom metadata field?

This is a request from my client to tweak an existing Perl script. However, it is the actual database structure on their end that confuses me.
The requirement looks pretty simple:
only pull records where _X begins with 1, 2, or 9.
However, the underlying database is not that simple, here is the guideline from their DBA:
"_X is a custom metadata field. The database stores this data in rows, not columns, within the customData table. In order to query the custom data table in an efficient manner you need to know the Field_ID for the custom field you get that from the fielddef table:
SELECT Field_ID FROM FieldDef WHERE Name = "_X";
This returns:
10012
"Now you can query CustomData. For example:
SELECT Record_ID FROM CustomData where Field_ID="10012" AND StringValue="2012-04";
He also suggests that in my case, probably it would be:
"SELECT Record_ID FROM CustomData where Field_ID="10012" AND (StringValue LIKE '1%' || StringValue LIKE '2%' || StringValue LIKE '9%')
The weird thing is that the existing Perl script doesn't contain anything like "Select Record_ID FROM" but all like "SELECT StringValue FROM".
So that is why I am very confused here: What is "store in rows, not in columns"? Why first query the Field_ID table then CustomData? I would not be able to communicate with any of them during this weekend but really wish to get some idea on the whole thing, hope experts can help me a little on sorting out the whole structure.
More info(Table schema):
http://pastebin.com/ZiDTCCC0
The existing perl script:(focus on lines 72-136)
http://pastebin.com/JHpikTeZ
Thanks in advance.
What they seem to be using is some kind of Entity-Attribute-Value model, with the entities stored as ints and explained in another table (FieldDef).
You explained pretty well how you queried it (although you can do it in one query, with a join or a subquery), and your problem seems to be that you don't know how the Perl script does it. Unfortunately, without us seeing the Perl script, we can't either :]

Mysql is not counting the rows of dates from my php script

I am trying to count the number of dates that occur for a specific mem_id, however, my count output is always "0"... heres my code:
$datechecker = $postdate;
//$postdate is a date variable that is posted via a form into mysql, stored as a DATE
$sql = mysql_query("SELECT * FROM members WHERE mem_id='$id' AND postdate='$datechecker'");
$Counter = mysql_num_rows($sql);
if($Counter >= 0) {
echo "$datechecker $Counter";
exit();
}
This is the output I get: 2011-01-01 0
Even though I have about 10 occurrences of 2011-01-01, so why does my count say "0"? Can anyone help me solve this, or provide an alternate?
echo the string before you mysql_query it, this will validate if the query is what you expect it to be. You can also use count(*) within the query, instead of using php's mysql_num_rows()
I also hope that you're sanitising your input before you're querying that!
1) You didn't clean $postdate, who knows if it conforms to MySQL's definition of DATE?
2) You didn't show us how your members table looks like. Is mem_id primary key? If it is, then of course you're going to get 1 row out of it.
3) You aren't checking whether your query succeeds or not, you immediately pass the resource_id to the mysql_num_rows table - which is a wrong way to perform counting anyway because MySQL (like any other relational database) has inbuilt mechanisms of counting rows based on criteria.
My guess is that your query is failing, seeing there's not $id specified.

Combining multiple Wordpress database queries

Forgive me for re-wording and re-asking this question, but the answers I received a couple weeks back didn't help much...
Basically, I'm looking to somehow combine multiple database queries in Wordpress to retrieve user IDs by searching for term in the 'usermeta' table, but only entries that have a certain 'meta_value'
I'm trying to combine:
$users = $wpdb->get_results("SELECT user_id, meta_value as 'business_name'
FROM $wpdb->usermeta
WHERE meta_key = 'business_name'");
AND:
$users = $wpdb->get_results("SELECT user_id, meta_value as 'business_description'
FROM $wpdb->usermeta
WHERE meta_key = 'business_description'");
To essentially have this:
$users = $wpdb->get_results("SELECT user_id, business_name, business_description
FROM
WHERE
business_name LIKE '%{$keyword}%' OR
business_description LIKE '%{$keyword}%'");
I've looked into INNER JOINs and subqueries, but cannot seem to find a good solution. I realize that I can get away with multiple queries, but this would be searching through possibly thousands of entries, so I'd like to optimize it as much as possible.
Hi #John:
If I understand your question correct (since you gave a technical example of what you were attempting but not a description of what end result you were trying to accomplish I'm not sure) it seems you are doing a user search? If yes, below is what I think you need.
<?php
// Load WordPress, but only for standalone example use
include '../wp-load.php';
// Make sure the database object is available
global $wpdb;
// Get value entered by the user
$keyword = $_GET['keyword'];
// This would be used in your code; the percent would confuse prepare() below
$keyword = "%{$keyword}%";
// Join each meta field as a separate join and reference the meta_key in the join
// prepare() below replaces "%s" with a quoted string value
$sql =<<<SQL
SELECT
users.user_nicename AS user_name,
bizname.meta_value AS business_name,
bizdesc.meta_value AS business_description
FROM
{$wpdb->users} AS users
INNER JOIN {$wpdb->usermeta} AS bizname
ON bizname.user_id=users.ID
AND bizname.meta_key='business_name'
INNER JOIN {$wpdb->usermeta} AS bizdesc
ON bizdesc.user_id=users.ID
AND bizdesc.meta_key='business_description'
WHERE 1=0
OR bizname.meta_value LIKE %s
OR bizdesc.meta_value LIKE %s
SQL;
// User prepare() to avoid SQL injection hacks
$sql = $wpdb->prepare($sql,$keyword,$keyword);
// Finally, get yer results!
$users = $wpdb->get_results($sql);
echo "<ul>";
foreach($users as $user) {
echo "<li>User= {$user->user_name}, Business= {$user->business_name}:{$user->business_description}</li>";
}
echo "<ul>";
The above is a complete working example you can copy to a file in the root of your website and call it something like /test.php allowing you to see it work by using a URL like this:
http://example.com/test.php?keyword=Accounting
Of course, this may be less performant at times than using multiple queries because of the query caching systems built-in to WordPress but it's impossible to tell without some benchmarking.
Hope this helps.
-Mike
P.S. By the way, I'm assuming you were not aware of it but since your prior question evidently hadn't gotten much WordPress love nor had this one I'll mention the WordPress Answers website which is a sister site to StackOverflow. Lots of WordPress enthusiasts are on hand over there to answer WordPress-specific questions.My experience with StackOverflow is they have some of the best developers on the web but few here have specific experience developing with WordPress so you end up with people here trying to answer MySQL questions without knowing the WordPress database schema and without knowing WordPress-specific best practices. Ask over at WordPress Answers and I think you'll an improved quality of answers to your WordPress-specific questions.
Can you post some details on the error messages you are receiving? The SQL here looks ok, but it's impossible to tell what the problem is without seeing the error messages.
For example, are you sure the $keyword field is being populated? How many results to return? Have you tried it without the WHERE statement or just a single OR to troubleshoot? Also, have you tried running this SQL directly on your server with some test keywords?
Give us more of an idea on what you have tried to fix the problem and we'll be able to assist further.
Kind Regards
Luke Peterson