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
";
Related
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
)
);
What's wrong with this query? It always returns NULL.
$recipes = $wpdb->get_results(
"SELECT ID FROM ".$wpdb->posts." WHERE post_author = %d AND post_status IN ('draft','publish') AND post_type = 'recipes' ", $current_user->ID
);
get_results takes output type as second parameter. You're missing prepare method if you want to do it like this. It should be something like
$recipes = $wpdb->get_results($wpdb->prepare ("SELECT ID FROM ".$wpdb->posts."
WHERE post_author = %d
AND post_status IN ('draft','publish')
AND post_type = 'recipes' ", $current_user->ID));
Code:
global $post;
global $wpdb;
$sel_query = "SELECT id FROM ".$wpdb->prefix."posts WHERE post_author = ".$current_user->ID." AND post_status IN ('draft','publish') AND post_type = 'recipes' ";
$totaldata = $wpdb->get_results($sel_query);
return $totaldata;
Im trying to do a select in my table posts where my categories can be action, adventure, comedy, scify.
First Im trying to find if there is something like "All" in sql to use in where clause:
$where = 'ALL';
$limit = '16';
SELECT * FROM posts WHERE category = '$where' ORDER BY visits ASC LIMIT $limit
But I dont see any information about, and ALL its not definitely working, so Im trying to write all my categories:
$where = 'action OR category = adventure OR category = comedy OR category= scifi';
$limit = '16';
SELECT * FROM posts WHERE category = '$where' ORDER BY visits ASC LIMIT $limit
But its not working, because I need to use '' in my categories name, but how I can do this in my example?
How can I use quotes in my categories here:
$where = 'action OR category = adventure OR category = comedy OR category= scifi';
My full code for this example:
if($type == 'action'){
$limit = '0,3';
$where = "category = 'action'";
}
else if($type == 'adventure'){
$limit = '0,5';
$where = "category = 'adventure'";
}
else if($type == 'comedy'){
$limit = '0,3';
$where = "category = 'comedy'";
}
else if($type == 'scifi'){
$where = "category = 'accao' OR category = 'adventure' OR category = 'comedy' OR category = 'scifi'";
$limit = '16';
}
$posts=
mysql_query("SELECT * FROM posts WHERE '$where' ORDER BY visits ASC LIMIT $limit")
or die(mysql_error());
If you EVERY category, then simply don't define the WHERE. Easy. Also it is not working because you are missing single quotes around every value.
Without defining WHERE you aren't comparing anything, so every row will be returned.
SELECT * FROM posts ORDER BY visits ASC LIMIT $limit
Also, fixed your code if i misunderstood you:
$where = "category = 'action' OR category = 'adventure' OR category = 'comedy' OR category= 'scifi'";
$limit = '16';
$sql = "SELECT * FROM posts WHERE $where ORDER BY visits ASC LIMIT $limit";
First of all, as already mentioned, it doesn't make sense to set a criteria to the query if all possible values are ok.
Secondly, I've added a possible improvement to your code:
<?php
$genres = array(
"action" => "0,3",
"adventure" => "0,5",
"comedy" => "0,3",
"scifi" => "16"
);
$type = "action";
if(!in_array($type, array_keys($genres))) {
//handle invalid input
}
$query = sprintf("SELECT * FROM `posts` WHERE `category` = '%s' LIMIT %s", $type, $genres[$type]);
echo $query;
?>
Last note: do not use mysql_* as they are deprecated. Look into PDO or mysqli_*.
If you stick to mysql_* functions, which you shouldn't, escape user input with e.g. mysql_real_escape_string -- notice the warning.
Good luck!
I know this subject has been covered before, and I've read about a dozen of the links provided by stackoverflow. None match my need.
I have 4 mysql queries using PHP for similar data, I'd like to lower that to one query and maybe put the results in an array that I can access. Here is my current code.
$id = $row[post_id];
$resulttwo = mysql_query("SELECT meta_value FROM wp_postmeta WHERE `post_id` = $id AND `meta_key` = 'length' ");
$temptwo = mysql_fetch_array($resulttwo);
$length[$id] = $temptwo[0];
$id = $row[post_id];
$resultthree = mysql_query("SELECT meta_value FROM wp_postmeta WHERE `post_id` = $id AND `meta_key` = 'location_city' ");
$tempthree = mysql_fetch_array($resultthree);
$trailcity[$id] = $tempthree[0];
$id = $row[post_id];
$resultfour = mysql_query("SELECT meta_value FROM wp_postmeta WHERE `post_id` = $id AND `meta_key` = 'location_state' ");
$tempfour = mysql_fetch_array($resultfour);
$trailstate[$id] = $tempfour[0];
$id = $row[post_id];
unset($tempfour);
$resultfour = mysql_query("SELECT meta_value FROM wp_postmeta WHERE `post_id` = $id AND `meta_key` = 'difficulty' ");
$tempfour = mysql_fetch_array($resultfour);
$difficulty[$id] = $tempfour[0].' difficulty';`
This should work:
$id = $row[post_id];
$result = mysql_query("SELECT meta_key, meta_value FROM wp_postmeta WHERE `post_id` = $id AND `meta_key` IN ('length', 'location_city', 'location_state', 'difficulty')");
$temp = mysql_fetch_assoc($result);
Array $temp will contain the meta_key along with the meta_value which you should be able to call like so $temp[length]. You can check the entire array with print_r($temp);
You should also stop writing new code using mysql_ functions as they are being deprecated and use mysqli_ or PDO instead.
This should be sufficient as you only care about the first row in each query.
SELECT meta_value FROM wp_postmeta WHERE post_id = $id AND meta_key IN ("length", "location_city", "location_state", "difficulty") LIMIT 4;
Damn too late! :/
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