I have written a custom query to retrieve data in WordPress and it works fine in my local so when I move to the real environment its syntax will be like?
$dbconnect = mysqli_connect('localhost','root','','goldenstatecanna');
$query = mysqli_query($dbconnect,"SELECT *
FROM wp_terms JOIN wp_termmeta
WHERE wp_terms.term_id = wp_termmeta.term_id
and wp_termmeta.meta_key = \"display_type\"
and wp_termmeta.meta_value != \"subcategories\"");
Need to know how to write that with Wordpress Syntax
You can use the wpdb Class, this global WordPress class is key for using queries. In fact, every function uses this class.
$query = "SELECT COUNT(apple) FROM fruits";
$wpdb->query($query);
You can achieve this by this code
global $wpdb;
$querystr = "
SELECT *
FROM $wpdb->terms termss JOIN $wpdb->termmeta termssmeta
WHERE termss.term_id = termssmeta.term_id
AND termssmeta.meta_key = 'display_type'
AND termssmeta.meta_value != 'subcategories' ";
$dataa = $wpdb->get_results($querystr);
print_r($dataa);
You can also refer this https://codex.wordpress.org/Displaying_Posts_Using_a_Custom_Select_Query
You should declare $wpdb as global before use it. It does work as an ORM for the Wordpress application, and there is a very extensive documentation about it, take a look, https://codex.wordpress.org/Class_Reference/wpdb
Related
I'm developing a Joomla 3 component and I'm trying to select data from database using the Joomla framework classes. I'm getting a error Not unique table/alias. What could be the reason ?.
Code Snippet...
$app = JFactory::getApplication();
$job_id = JRequest::getVar('Jobid', null);
try {
$db = JFactory::getDbo();
$query = $db->getQuery(true);//Here Was The Problem
$query->select(array('A.state AS approval_state', 'A.*', 'B.*', 'C.district_name', 'D.educational_qualification', 'E.current_job_status'))
->from($db->quoteName('#__pes_job_provider_request_cv_info') . 'AS A')
->join('LEFT', '#__pes_jobseeker_profile AS B ON B.jobseeker_profile_id = A.jobseeker_profile_id')
->join('LEFT', '#__pes_district AS C ON C.district_id = A.district_id')
->join('LEFT', '#__pes_highest_educational_qualification AS D ON D.highest_educational_qualification_id = B.highest_educational_qualification_id')
->join('LEFT', '#__pes_current_job_status AS E ON E.current_job_status_id = B.current_job_status_id')
->where($db->quoteName('A.job_order_registration_id') . ' = ' . $db->quote($job_id))
->order('B.name_in_full ASC');
$db->setQuery($query);
$results = $db->loadObjectList();
Thank You.
OK ! I figured out the reason.
The reason why this happened is that I haven't instantiated the query object as a new query.
i.e. $query = $db->getQuery();
So, in order to resolve the issue I simply gave the parameter boolean true for the query method
i.e. $query = $db->getQuery(true);
I want to build the below query using joomla inbuilt database class.
SELECT *
FROM table_name
ORDER BY id DESC
LIMIT 1
This is the query I have built up to now.
$db =& JFactory::getDBO();
$query = $db->getQuery(true);
$query->select($db->nameQuote('*'));
$query->from($db->nameQuote(TABLE_PREFIX.'table_name'));
$db->setQuery($query);
$rows = $db->loadObjectList();
I don't know how to add the limit(LIMIT 1) to the query. Can someone please tell me how to do it? Thanks
Older than Joomla 3.0
$db = JFactory::getDBO();
$query = $db->getQuery(true);
$query->select('*')
->from($db->nameQuote('#__table_name'))
->order($db->nameQuote('id').' desc');
$db->setQuery($query,0,1);
$rows = $db->loadObjectList();
$db->setQuery function takes 3 parameters. The first one being the query, then the start, then the limit. We can limit records as shown above.
Newer than Joomla 3.0
setLimit(integer $limit, integer $offset)
If you want just one row
$query->setLimit(1);
Read more
This should work as well:
$query->setLimit(1);
Documentation: http://api.joomla.org/cms-3/classes/JDatabaseQueryLimitable.html
SetLimit doesn't work for me in Joomla 3.4.x, so try:
Within the model:
protected function getListQuery()
{
// Create a new query object.
$db = JFactory::getDBO();
$query = $db->getQuery(true);
// Select some fields
$query->select('*');
$query->from('#__your_table');
$this->setState('list.limit', 0); // 0 = unlimited
return $query;
}
Davids answer: https://joomla.stackexchange.com/questions/4249/model-getlistquery-fetch-all-rows-with-using-jpagination
Run that before the model calls getItems and it will load all the
items for you.
A few caveats with this.
You can also do this outside the model, so if for instance you were in
your view. You could do the following:
$model = $this->getModel(); $model->setState('list.limit', 0);
Sometimes you can do this too early, before the model's state has been
populated, which will cause the model to get rebuilt from the user
state after you have set the limit, basically overriding the limit.
To fix this, you can force the model to populate its state first:
$model = $this->getModel(); $model->getState();
$model->setState('list.limit', 0); The actual populateState method is
protected, so outside the model you can't call it directly, but any
call to getState will make sure that the populateState is called
before returning the current settings in the state.
Update: Just had to revisit this answer, and I can confirm, both the methods
setLimit & order are working if used as below.
$query->order($db->qn($data->sort_column_name) . ' ' . $data->sort_column_order);
$query->setLimit($length,$start);
OLD ANSWER
As of 08/Sept/14 The solutions from #Dasun or #escopecz arent working for me on J3.x
but this old trick is working for me which is nice,
$query->order($db->qn('id') . ' DESC LIMIT 25');
And About your specific requirement of wishing to fetch only 1 row you could use :
$rows = $db->loadObject();
I use Yii Framework and i need to build difficult query with many conditions.
I'm filling 2 arrays $conditions and $values.
And i have one problem.
Below is example
When i use
$usersId = '1,2';
$conditions[] = 'e.user_id IN(:usersId)';
$values[':usersId'] = $usersId;
I get only value from user_id = 1
When i'm not use option and write manually
$usersId = '1,2';
$conditions[] = 'e.user_id IN(' . $usersId . ')';
no problem.
Of course i can use second construction, but it seems not very good.
You should addInCondition
$criteria->addInCondition('e.user_id',array(1,2));
Yii way would be to use CDbCriteria addInCondition function
$usersId = array(1,2); //must be array
$criteria=new CDbCriteria();
$criteria->addInCondition('user_id',$usersId);
$result = MyModel::model()->findAll($criteria);
$values[':usersId'] = $usersId;
If I understand your wuestion correctly, you can use the BindParam function in yii?
Instead of this - $values[':usersId'] = $usersId;
Write this - $command->BindParam(':usersId', $usersId, PDO::PARAM_STR);
Very simply, you're binding your parameters to your command statement.
Hope it works!
I have a custom table called wp_purchases that is added to by a Paypal IPN, it has the columns post_id, purchase_id, username, email and changes:
$user = $_POST['username'];
$post_id = $post->ID;
global $wpdb;
$wpdb->purchases = $table_prefix . 'purchases';
$result = $wpdb->query("SELECT * FROM $wpdb->purchases WHERE username = $user AND post_id = $post_id");
if ($result) {...
I'm just trying to check if there is a purchase under a certain username in a single .php theme page and then perform an operation unrelated to the $result.
It won't work though, any way I try it comes up with null. Is it something to do with using $wpdb->purchases or not including a certain file or something else? I've also tried it with get_results and get_row with no luck.
Try this :
$result = $wpdb->query("SELECT * FROM `".$wpdb->purchases."` WHERE username = '$user' AND post_id = '$post_id';");
I gave up and just used
$result = $wpdb->query("SELECT * FROM wp_purchases WHERE username = $user AND post_id = $post_id");
because it's for a single site and doesn't really need the table prefix, it'll always be wp_
I know it's too late for this answer, but I'll still post it for the sake of others who are also having similar issue.
You mentioned that the query still returns nothing even after removing the WHERE part, have you tried to echo $wpdb->purchases variable? It might just returning you a string "purchases" instead of "wp_purchases" (assuming that your table prefix is "wp_"). Try using $wpdb->prefix instead of $table_prefix, or $wpdb->base_prefix if you got a multisite.
$wpdb->purchases = $wpdb->prefix . 'purchases';
What type of username? I assume it stores string data. So variable $user must be quoted:
"SELECT * FROM $wpdb->purchases WHERE username = \"$user\" AND post_id = $post_id"
I have a join using mysql in php and want to turn that into a pdo query how do i do that?
Also how do I get the results of this query and display it.
Code is below:
$query = "SELECT * FROM pages LEFT JOIN templates ON pages.template_id = templates.template_id WHERE pages.page_Title = '".$getVars['page']."'";
I am new to PDO so this might sound like a very basic question.
Thanks in Advance
Why don't people even look at the PHP reference for these basic questions? See http://be2.php.net/manual/en/pdo.connections.php. It's all there, you don't have to change anything to the query in order to run it with PDO.
You could however try using a prepared statement, and pass the title as a parameter :
$dbh = new PDO('mysql:host=localhost;dbname=database', $user, $pass);
$stmt = $dbh->prepare("SELECT * FROM pages LEFT JOIN templates ON pages.template_id = templates.template_id WHERE pages.page_Title = ?");
if ($stmt->execute(array($getVars['page']))) {
while ($row = $stmt->fetch()) {
print_r($row);
}
}