Wrong result with php - 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

Related

Is it possible to add if statments inside php sql query

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
)
);

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
";

MySQLi select from two table with limit

I have been try to combine two tables from mysql database, the two tables are status and status_reply both have the same columns number and name, that is id, account_name, author, postdate, data Please a help will be appreciated.
$limit = "LIMIT 0, 10";
$query = mysqli_query($db_conx, "(SELECT * `status` as type from status WHERE data LIKE '%".$tag."%' ORDER BY postdate DESC $limit)
UNION (SELECT * `status_reply` as type from status_reply WHERE data LIKE '%".$tag."%' ORDER BY postdate DESC $limit)");
//$query = mysqli_query($db_conx, "SELECT * FROM status WHERE data LIKE '%$tag%' ORDER BY postdate DESC $limit");
$statusnumrows = mysqli_num_rows($query);
while ($row = mysqli_fetch_array($query, MYSQLI_ASSOC)) {
$statusid = $row["id"];
$account_name = $row["account_name"];
$author = $row["author"];
$postdate = $row["postdate"];
$data = $row["data"];
$data = nl2br($data);
$data = str_replace("&","&",$data);
$data = stripslashes($data);
$statuslist .= '<div id="status_'.$statusid.'" class="status_boxes"><div><b>Ivotised by '.$author.' '.$postdate.':</b>
<article>'.$data.'</article>
</div></div>';
}
Use backquotes ` for field names instead of straight quotes '
Don't forget to quote $tag to protect from an SQL injection: mysqli_real_escape_string
Remember, that is you want to search literally for LIKE wildcard characters "%", "_" as well as backslash. You need to escape them too, using: $tag = addcslashes($tag, '\%_');
$limit = "LIMIT 0, 10";
$query = mysqli_query($db_conx, "
(SELECT `status` as type from status WHERE data LIKE '%".$tag."%'
ORDER BY postdate DESC $limit)
UNION
(SELECT `status_reply` as type from status_reply WHERE data LIKE '%".$tag."%'
ORDER BY postdate DESC $limit)");
I realized that I have to remove the type in both status and status_reply as references to the tables and identified each of the columns by their names. Am curious about it too!
$query = mysqli_query($db_conx, "
(SELECT id, account_name, author, postdate, data from status WHERE data LIKE '%".$tag."%'
ORDER BY postdate DESC $limit)
UNION
(SELECT id, account_name, author, postdate, data from status_reply WHERE data LIKE '%".$tag."%'
ORDER BY postdate DESC $limit)");

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'];

Is there a more efficient way to write these 4 MYSQL Queries to use fewer queries?

My current queries. Can I combine them in to fewer to get the same result? I am trying to get specific information about the trail into an array named $trail.
$result = mysql_query("SELECT meta_value FROM wp_postmeta WHERE `post_id` = $id AND `meta_key` = 'location_city' ");
$result = mysql_fetch_array($result);
$trail[city] = $result[0];
$result = mysql_query("SELECT meta_value FROM wp_postmeta WHERE `post_id` = $id AND `meta_key` = 'length' ");
$result = mysql_fetch_array($result);
$trail[length] = $result[0];
$result = mysql_query("SELECT meta_value FROM wp_postmeta WHERE `post_id` = $id AND `meta_key` = 'location_state' ");
$result = mysql_fetch_array($result);
$trail[state] = $result[0];
$result = mysql_query("SELECT meta_value FROM wp_postmeta WHERE `post_id` = $id AND `meta_key` = 'difficulty' ");
$result = mysql_fetch_array($result);
$trail[difficulty] = $result[0];
$result = mysql_query("SELECT guid FROM wp_posts WHERE `post_parent` = $id AND `post_type` = 'attachment' ");
$result = mysql_fetch_array($result);
$trail[image] = $result[0];
This will work for the meta_values:
SELECT meta_value, meta_key
...
WHERE (post_id = $id) AND (meta_key IN ('location_city', 'length', ...)
The guid query will probably be better off run as a separate one. If you insist on reducing to a single query call, then a union would do
SELECT 'meta' AS source, meta_value, meta_key
WHERE ...
UNION ALL
SELECT 'guid' AS source, guid, null
FROM ...
WHERE post_parent = $id and post_type = 'attachment'
then use this derived 'source' field to figure out which value(s) belong where.
If you want the data in columns, then you could JOIN the queries:
SELECT lc.meta_value Location_City,
l.meta_value Location,
ls.meta_value LocationState,
d.meta_value Difficulty,
p.guid
FROM wp_postmeta lc
LEFT JOIN wp_postmeta l
on lc.`post_id` = l.`post_id`
and l.`meta_key` = 'length'
LEFT JOIN wp_postmeta ls
on lc.`post_id` = ls.`post_id`
and ls.`meta_key` = 'location_state'
LEFT JOIN wp_postmeta d
on lc.`post_id` = d.`post_id`
and d.`meta_key` = 'difficulty'
LEFT JOIN wp_posts p
on lc.`post_id` = p.`post_parent`
and p.`post_type` = 'attachment'
WHERE lc.`post_id` = $id
AND lc.`meta_key` = 'location_city'
SELECT meta_value FROM wp_postmeta WHERE `post_id` = $id AND (`meta_key` = 'difficulty' OR `meta_key` = 'location_state' OR `meta_key` = 'length' OR `meta_key` = 'location_city' )

Categories