Is it possible to add if statments inside php sql query - php

I have php function with query I want to add different Order by ASC/DESC depending on the form value the user selects so I had if statement inside the query line.
I tried but I get no error and no result, but if I without the if it works.
<?php
SELECT * FROM Customers
if(!empty($registro_asc_desc)){
ORDER BY user_registered DESC,
} else if(!empty($post_asc_desc)){else {
ORDER BY postDESC,
}
?>

You can try this way:
$sql = "SELECT * FROM Customers";
if (!empty($registro_asc_desc)) {
$sql .= " ORDER BY user_registered DESC";
} else if (!empty($post_asc_desc)) {
$sql .= " ORDER BY post DESC";
}

Unfortunately none of the above worked; no error but still no result! Here is my full query, I want to add the if statements on the line of the ORDER BY
function get_users_by_post_count( $post_type = 'advert' ) {
global $wpdb;
$users = $wpdb->get_results(
$wpdb->prepare(
"SELECT {$wpdb->users}.ID, p.post_count, display_name, user_registered
FROM {$wpdb->users}
LEFT JOIN (
SELECT post_author, COUNT(*) AS post_count
FROM {$wpdb->posts} WHERE post_type = 'advert'
GROUP BY post_author
) p ON {$wpdb->users}.id = p.post_author
WHERE user_registered between '2021/10/01' and '2022/02/01'
ORDER BY p.post_count ASC,
user_registered LIMIT 5",
$post_type
)
);
return $users;
}

I did try but did not work here example with the example mention above
$users = '';
$users = $wpdb->get_results(
$wpdb->prepare(
"SELECT {$wpdb->users}.ID, p.post_count, display_name, user_registered
FROM {$wpdb->users}
LEFT JOIN (
SELECT post_author, COUNT(*) AS post_count
FROM {$wpdb->posts} WHERE post_type = 'advert'
GROUP BY post_author
) p ON {$wpdb->users}.id = p.post_author
WHERE user_registered between '2020/01/01' and '$data_final_format';
if (!empty($registro_asc_desc)) {
$users.= 'ORDER BY user_registered DESC';
} else if (!empty($post_asc_desc)) {
$users.= 'ORDER BY p.post_count DESC';
}
user_registered LIMIT 20",
$post_type
)
);

Related

WordPress: SQL query to get list of years when posts have been published with language variable (Polylang)

Please help to modify an SQL query. I have such code:
public function get_posts_years($lang = '')
{
global $wpdb;
$where = $wpdb->prepare("WHERE post_type = %s AND post_status = 'publish'", self::POST_TYPES);
$query = "SELECT YEAR(post_date) AS `year`, count(ID) as posts FROM $wpdb->posts $where GROUP BY YEAR(post_date) ORDER BY post_date DESC";
return $wpdb->get_results($query) ?? [];
}
For now I get result only for default language. I need to implement a language variable to this query. Language plugin is Polylang.

I'm struggling with the WHERE IN query

I am not able to use this code. I've echoed the implode (and it works perfectly) but I cannot seem to get it to work with the WHERE IN query.
I've tried echo the import, which works, and the code works perfectly when I remove the WHERE IN, so I know the elements within 'etc etc' are working, too.
$filter_category = "SELECT * FROM `youcard_wp`.`bc_term_relationships`
WHERE term_taxonomy_id = '57'";
$result_c = $conn90->query($filter_category);
while($row_c = $result_c->fetch_assoc()){
$category_filter[] = $row_c['object_id'];
}
echo implode(',', $category_filter); // <- works great
$get_offer_list = "
SELECT * FROM `youcard_wp`.`bc_posts`
WHERE `ID` IN ('".implode(',', $category_filter)."')
AND post_status = 'publish'
AND post_type = 'portfolio'
ORDER BY menu_order ASC
";
$result = $conn90->query($get_offer_list);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
etc etc etc...
You don't need any of that. Instead use this...
SELECT x.columns
, x.you
, x.actually
, x.want
FROM bc_posts x
JOIN bc_term_relationships y
ON y.object_id = x.id
WHERE x.post_status = 'publish'
AND x.post_type = 'portfolio'
AND y.term_taxonomy_id = 57
ORDER
BY x.menu_order ASC
You are surrounding the whole IN list with a pair of single quotes, whereas you would need to quote each individual value.
Consider:
$get_offer_list = "
SELECT *
FROM `youcard_wp`.`bc_posts`
WHERE
`ID` IN ('" .implode("','", $category_filter)."')
AND post_status = 'publish'
AND post_type = 'portfolio'
ORDER BY menu_order ASC
";
If IDs are actually numeric values and not strings, then you do not need quotes at all:
$get_offer_list = "
SELECT *
FROM `youcard_wp`.`bc_posts`
WHERE
`ID` IN (" .implode(",", $category_filter).")
AND post_status = 'publish'
AND post_type = 'portfolio'
ORDER BY menu_order ASC
";

select down and up votes for each post php mysql

I have a forum where users can post questions and can upvote and downvote.
I want to get the upvote and downvote of each post.
What i did previously was do that in 3 sets queries.
$data = mysqli_query($con,"select * from posts");
while($row = mysqli_fetch_assoc($data)){
$pid = $row['post_id'];
$up = mysqli_fetch_assoc(mysqli_query("SELECT COUNT(*) as c FROM up WHERE post_id = $pid"))['c'];
$down = mysqli_fetch_assoc(mysqli_query("SELECT COUNT(*) as c FROM down WHERE post_id = $pid"))['c'];
}
Can anyone show me how can i do these things in one single query because if a get a lot of posts in 1st query then there will be lots of queries to do.
You can use subqueries and put everything in the first query.
This could be a good start :
$data = mysqli_query($con, "select posts.*, " .
"(SELECT COUNT(*) FROM up WHERE post_id = posts.post_id) as totalUp, " .
"(SELECT COUNT(*) FROM down WHERE post_id = posts.post_id) as totalDown " .
"from posts");
while($row = mysqli_fetch_assoc($data)){
// ...
}
you can use corelated subquery for this where upvotes
and downvotes are counted based on the post id
SELECT p.*,
( select count(*) from up where post_id = p.post_id ) as upVotesCount,
( select count(*) from down where post_id = p.post_id ) as downVotesCount,
FROM posts p

Sort the results of a query using results of another query

Im working on a message board of some sort and i have everything up an running except one little part, the threads need to be sorted by the date/time of the latest post in them (standard forum format), which im having lots of trouble wrapping my head around.
This is the querys im using, i know its not pretty and its not safe, i will be reworking them once i learn how to do it properly.
$sql = "SELECT Thread_ID, Thread_Title, Board_ID, Author FROM threads WHERE Board_ID='$Board_ID' LIMIT $offset, $rowsperpage";
$result = mysql_query($sql, $conn) or trigger_error("SQL", E_USER_ERROR);
while ($row = mysql_fetch_assoc($result))
{
$Thread_ID = $row['Thread_ID'];
$Thread_Title = $row['Thread_Title'];
$Board_ID = $row['Board_ID'];
$Author = $row['Author'];
$getauthor = mysql_query("SELECT * FROM members WHERE Member_ID='$Author'");
while ($row = mysql_fetch_assoc($getauthor))
{
$Post_Author = $row['Post_As']; }
$postcount = mysql_query("SELECT Post_ID FROM posts WHERE Thread_ID='$Thread_ID'");
$Posts = mysql_num_rows($postcount);
$getlatest = mysql_query("SELECT * FROM posts WHERE Thread_ID='$Thread_ID' ORDER by Post_DateTime DESC LIMIT 1");
while ($row = mysql_fetch_assoc($getlatest))
{
$Post_DateTime = time_ago($row['Post_DateTime']);
$Member_ID = $row['Member_ID']; }
$getmember = mysql_query("SELECT * FROM members WHERE Member_ID='$Member_ID'");
while ($row = mysql_fetch_assoc($getmember))
{
$Post_As = $row['Post_As']; }
So what im trying to do is Sort $sql by $getlatest, i tried adding another query above $sql that did basically the same as $getlatest and then had $sql order by that but alas it just broke everything.
I know i have to make a variable to sort the $sql by but its that variable thats driving me mad.
any help would be appreciated, thanks.
current error message as requested:
Fatal error: SQL - Unknown column 'posts2.LatestPost' in 'on clause' - SELECT threads.Thread_ID, threads.Thread_Title, threads.Board_ID, threads.Author, Sub1.LatestPost, Sub1.PostCount, members.Post_As, members2.Member_ID AS LastPostMemberID, members2.Post_As AS LastPostMemberPostAs FROM threads INNER JOIN (SELECT Thread_ID, MAX(posts.Post_DateTime) AS LatestPost, COUNT(*) AS PostCount FROM posts GROUP BY Thread_ID) Sub1 ON threads.Thread_ID = Sub1.Thread_ID INNER JOIN members ON threads.Author = members.Member_ID INNER JOIN posts posts2 ON posts2.Thread_ID = Sub1.Thread_ID AND posts2.LatestPost INNER JOIN members members2 ON members2.Member_ID = posts2.Member_ID WHERE threads.Board_ID='1' ORDER BY Sub1.LatestPost DESC LIMIT 0, 25 in C:\wamp\www\forum\include\threads.php on line 86
You should be able to do it using something like this for your first query:-
$sql = "SELECT threads.Thread_ID, threads.Thread_Title, threads.Board_ID, threads.Author, MAX(posts.Post_DateTime) AS LatestPost
FROM threads
LEFT OUTER JOIN posts ON threads.Thread_ID = posts.Thread_ID
WHERE threads.Board_ID='$Board_ID'
GROUP BY SELECT threads.Thread_ID, threads.Thread_Title, threads.Board_ID, threads.Author
ORDER BY LatestPost DESC
LIMIT $offset, $rowsperpage";
EDIT
Not tested the following but looking at your selects I think you could probably put it together into a single SELECT. Something like this:-
$sql = "SELECT threads.Thread_ID, threads.Thread_Title, threads.Board_ID, threads.Author, Sub1.LatestPost, Sub1.PostCount, members.Post_As, members2.Member_ID AS LastPostMemberID, members2.Post_As AS LastPostMemberPostAs
FROM threads
INNER JOIN (SELECT Thread_ID, MAX(posts.Post_DateTime) AS LatestPost, COUNT(*) AS PostCount FROM posts GROUP BY Thread_ID) Sub1
ON threads.Thread_ID = Sub1.Thread_ID
INNER JOIN members
ON threads.Author = members.Member_ID
INNER JOIN posts posts2
ON posts2.Thread_ID = Sub1.Thread_ID AND posts2.Post_DateTime = Sub1.LatestPost
INNER JOIN members members2
ON members2.Member_ID = posts2.Member_ID
WHERE threads.Board_ID='$Board_ID'
ORDER BY Sub1.LatestPost DESC
LIMIT $offset, $rowsperpage";
$result = mysql_query($sql, $conn) or trigger_error("SQL", E_USER_ERROR);
while ($row = mysql_fetch_assoc($result))
{
$Thread_ID = $row['Thread_ID'];
$Thread_Title = $row['Thread_Title'];
$Board_ID = $row['Board_ID'];
$Author = $row['Author'];
$Post_Author = $row['Post_As'];
$Posts = $row['PostCount'];
$Post_DateTime = time_ago($row['LatestPost']);
$Member_ID = $row['LastPostMemberID'];
$Post_As = $row['LastPostMemberPostAs'];

Wrong result with php

I am running a script to get some posts from a database.
Here is the script:
private function getItems()
{
$this->dbConnect($detailsTable);
mysql_select_db(DB_NAME);
mysql_query('SET NAMES utf8');
mysql_query('SET CHARACTER SET utf8');
$result = mysql_query('SELECT *
FROM wp_posts, wp_term_relationships,wp_term_taxonomy
WHERE wp_posts.post_status = "publish"
AND wp_term_relationships.object_id = id
AND wp_term_taxonomy.taxonomy= "category"
AND !(wp_term_taxonomy.term_taxonomy_id = 11)
AND wp_term_relationships.term_taxonomy_id = wp_term_taxonomy.term_taxonomy_id
ORDER BY wp_posts.post_date DESC LIMIT 25', LINK);
mysql_close(LINK);
$items = '';
while($row = #mysql_fetch_array($result))
{
$title = UTFayar($row['post_title']);
$content = UTFayar($row['post_content']);
$items .= '<item id="'.$row["ID"].'">
<title><![CDATA['.$title.']]></title>
<description><![CDATA['. $content .']]></description>
<pubDate>'.date('D, j M Y H:i:s T', strtotime($row['post_date'])).'</pubDate>
<category>'.$row['post_category'].'</category>
</item>';
}
$items .= '</channel>
</rss>';
return $items;
}
The problem is that some posts are in 3+ categories.
So I get a wrong result, I get same post 3+ times successively. I need that this post even if is at more then one category to be showed in my rss only 1 time.
EIDTED:
Here is right code, if some one will need it:
private function getItems()
{
$this->dbConnect($detailsTable);
mysql_select_db(DB_NAME);
mysql_query('SET NAMES utf8');
mysql_query('SET CHARACTER SET utf8');
//$result = mysql_query ('SELECT * FROM wp_posts WHERE post_status="publish" and post_category!=17 and post_category!=18 ORDER BY post_date DESC LIMIT 20', LINK);
$result = mysql_query('SELECT
ID
, post_title
, post_content
, post_date
, group_concat(DISTINCT post_category ORDER BY post_category DESC SEPARATOR ", " ) as "categories"
FROM wp_posts, wp_term_relationships,wp_term_taxonomy
WHERE wp_posts.post_status = "publish"
AND wp_term_relationships.object_id = id
AND wp_term_taxonomy.taxonomy= "category"
AND !(wp_term_taxonomy.term_taxonomy_id = 11)
AND wp_term_relationships.term_taxonomy_id = wp_term_taxonomy.term_taxonomy_id
GROUP BY ID, post_title, post_content, post_date ORDER BY wp_posts.post_date DESC LIMIT 25', LINK);
mysql_close(LINK);
$items = '';
while($row = #mysql_fetch_array($result))
{
$title = UTFayar($row['post_title']);
$content = UTFayar($row['post_content']);
$items .= '<item id="'.$row["ID"].'">
<title><![CDATA['.$title.']]></title>
<description><![CDATA['. $content .']]></description>
<pubDate>'.date('D, j M Y H:i:s T', strtotime($row['post_date'])).'</pubDate>
<category>'.$row['categories'].'</category>
</item>';
}
$items .= '</channel>
</rss>';
return $items;
}
The problem is that you need to deal with the categories in some way.... rolling them up and displaying them in a list with commas may be a good way to deal with it.
mysql has a nice function called "GROUP_CONCAT" http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html#function_group-concat
your query would be
SELECT
ID
, post_title
, post_content
, post_date
, group_concat(DISTINCT post_category ORDER BY post_category DESC SEPARATOR ', ' ) as `categories`
FROM wp_posts, wp_term_relationships,wp_term_taxonomy
WHERE wp_posts.post_status = "publish"
AND wp_term_relationships.object_id = id
AND wp_term_taxonomy.taxonomy= "category"
AND !(wp_term_taxonomy.term_taxonomy_id = 11)
AND wp_term_relationships.term_taxonomy_id = wp_term_taxonomy.term_taxonomy_id
GROUP BY ID
, post_title
, post_content
, post_date
ORDER BY wp_posts.post_date DESC

Categories