Combining multiple Wordpress database queries - mysql

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

Related

MySql Query for selecting users according to the Date of Today

$user_countday = $wpdb->get_var( "SELECT * FROM {$wpdb->prefix}users WHERE (DATE('user_registered') = DATE(NOW())" );
print_r($user_countday);
I am using the above Query for selecting all registerd users of today in wordpress but this is not displaying any answer.
For trying many hours, I didn't got any solution.
Where is the problem in my code?
I am not very familiar with WordPress, but an educated guess is that you are using the wrong function to load results. You are using get_var while you may need to use get_results.
1 more parentheses is needed from dbms query should returned row if wordpress is accurate
( "SELECT * FROM {$wpdb->prefix}users WHERE DATE(user_registered) = getdate())" )

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.

odd sql error, variable not being recognized correctly

I'm currently in hour two of this issue, I can't explain it so I will simply show what is going on. I don't know if this matters at all, but I am using the linkedIN API to retrieve a user's linkedIn unique ID.
In English, what I'm doing:
User Signs in with LinkedIn
I read-in user's LinkedIn ID (returned from the API)
If ID exists in database, say "hello", if not, show them a form to register
The issue I am having:
The following line works and properly returns the 1 user I have in the database with a linkedIn ID of OtOgMaJ2NM
$company_data = "SELECT * FROM s_user WHERE `LI_id` = 'OtOgMaJ2NM'";
The following query returns no results - using the same database with the same record in the table s_user:
$linkedIn_id = "<?js= id ?>";
echo $linkedIn_id;
The following code outputs OtOgMaJ2NM with no trailing spaces.
So far so good ... expcept when I run the query this time using the variable, no records are returned!
$company_data = "SELECT * FROM s_user WHERE `LI_id` = '$linkedIn_id'";
Further notes:
When I echo $company_data the same query is displayed when I use the variable as did when I used the plain text version of the query.
Anyone have ANY ideas?
Thanks,
Evan
I can only assume that when echoing variables it strips the tags, so when you're using it with the query you're actually saying:
$company_data = "SELECT * FROM s_user WHERE `LI_id` = '<?js= OtOgMaJ2NM ?>'";
I could be wrong, but have you tried stripping the tags from the variable?
If you send the variable between the "", the MySQL engine will search for $linkedIn_id literally and not for its content.
Seems you are using php, but I'm not sure about the right syntax. Take a look in the docs.

Issue With a Mysql Query Displaying A columns Data

I am trying to run this query from a drop down menu, the category and the destination data are working fine, just not the subcategory, it's probably an issue with my Html or Javasscript but i wanted to get the opinion of an expert with MYSQL if poss? I am quite new to PHP and MYSQL, but learning fast, Not sure my HTML will post here so i will just ask if someone can confirm that my query should work ok. Thanks guys.
$category=$_POST['Category'];
$subcategory=$_POST['Subcategory'];
$destination=$_POST['Destination'];
$result = mysql_query("SELECT * FROM travel WHERE Category='$category' AND Subcategory='$subcategory' AND Destination='$destination'")
or die(mysql_error());
$row = mysql_fetch_array( $result ) ;
Not sure if it's a culprit in your case, but you have to escape data coming from a user before passing it to the query :
$category=mysql_real_escape_string($_POST['Category']);
$subcategory=mysql_real_escape_string($_POST['Subcategory']);
$destination=mysql_real_escape_string($_POST['Destination']);
....

SHA salt in MySQL query

I am setting a cookie. Something like:
$_COOKIE['test'] = SHA1('124'.'mysalt');
Now 124 is my id which I want. So in my MySQL table, I am trying to run a query like:
$sql = ("SELECT * FROM users WHERE SHA1(`id`) = '".mysql_real_escape_string($_COOKIE['test'])."'");
How to add the "mysalt" to the SQL query? Because else I want get the correct id.
Use can use Concat() for that.
SELECT ... Sha1( Concat(`id`, 'mysalt') )=...
The query should be:
$sql = ("SELECT * FROM users WHERE SHA1(CONCAT(`id`,`mysalt`)) = '".mysql_real_escape_string($_COOKIE['test'])."'");
if I understand correctly what you're trying to do.
The solutions already provided probably will work just fine, however are you certain you want to do this? If the field "id" is really a distinct identification you can use "LIMIT 1" to stop mysql from searching thru all your items. Another thing is, why don't you use a separate precomputed field for this? I mean in every query mysql unnecessarily needs to compute all these sha1 values.. One last thing. I'm uncertain why you are using your approach, but my best guess is to implement some sort of session key. I thing this is a bad idea for a couple of reasons: If someone gets holds on your salt, he has access to all your accounts. If someone sniffs one "session" he can reuse it whenever he wants to. Choosing a weak salt could have serious consequences. HTH.
Use CONCAT:
$sql = ("SELECT * FROM users WHERE SHA1(CONCAT(`id`,'mysalt')) = '".mysql_real_escape_string($_COOKIE[''test''])."'");