PHP SQL search systems - php

I am trying to build a search system. I used a mySQL system but I have little experience and I do not quite get it.
I want to search by the field in the database called post_title and then get the URL, date
I would also like to be able to search by tags. For that we need to join the table wp_term_relationships which will give us a column with post id's in it and a column with tag id's. From that we can then work out which tags apply.
My attempt failed miserably with FATAL ERROR
<?php
$proto = $_GET['proto'];
$terms = $_GET['f'];
if($proto == 'inline'){
$searchpattern = mysql_real_escape_string(strtoupper($terms));
$list = mysql_query("SELECT id,
post_title, post_date
FROM wp_posts
WHERE post_title LIKE '%$searchpattern%'
)
ORDER BY post_date;");
while ($row = mysql_fetch_array($list)) {
$title = $row['post_title'];
$date = $row['post_date'];
$url = $row['guid'];
$date = date($date, 'd M Y');
$return .= '<li>
'.$firstname.' '.$lastname.'<br /><span style="font-size:10px; color:#555;">'.$email.'</span>
</li>
<div class="title"><b>SEARCH RESULTS</b></div>
<img src=""/>'. $title .' - <span>'. $date .'</span>';
}
}
?>

$list = mysql_query("SELECT id, post_title, post_date
FROM wp_posts
WHERE post_title LIKE '%$searchpattern%') ORDER BY post_date;");
You have unexpected ")" before the "ORDER" operator.

You have an open bracket before the ORDER BY. Maybe that's what causing the problem

Related

MySql Query for WordPress Recent Posts Need to Link to Individual Posts

This code displays the most recent 3 posts in WordPress. However, when following the links, every link connects to the most recent post, not the post associated with the excerpt. I need the excerpt links to connect to their associated full posts.
I did not code this and I realize it's deprecated. I've also tried WP recent posts function and shortcodes which don't work. The PHP code is so messed up that it causes lots of issues. I have very limited knowledge of MySql.
$sql = mysql_query("SELECT * from wp_term_relationships where term_taxonomy_id = '3' ORDER BY object_id DESC LIMIT 3 ");
while ($row = mysql_fetch_assoc($sql))
{
$object_id = $row['object_id'];
$sql_posts = mysql_query("SELECT * From wp_posts where ID = '$object_id' AND post_status = 'publish' AND post_type = 'post' ORDER BY ID DESC LIMIT 3");
while($row_posts = mysql_fetch_assoc($sql_posts))
{?>
<div class=" gaming_news_col col-lg-4 col-md-4 col-sm-4">
<h4><a href="<?php the_permalink() ?>"><?php echo $row_posts['post_title'];?></h4>
<p><?php
$content = $row_posts['post_content'];
$post_content = myTruncate($content, 150, " ");
echo $post_content;
?></p>
The method myTruncate cuts the text to some specific range, for instance, at your case, it will show only first 150 characters. If you want to show the full text, do not use myTruncate at all. Just echo the content.
$content = $row_posts['post_content'];
echo $post_content;
This should do the trick and not cut the text to specified limit.

Query database with comment meta

I have a wordpress comment box with 2 custom files, name and country, which get written to the database with the meta_key tag as comment_name and comment_country. What I need to do is display these comments which needs to include the actual comment, as well as the values of the 2 custom fields. I need to query the database as I need to retrieve ALL comments, not just comments for that particular page.
The code I (kind of) have is:
<?php
global $wpdb;
$querystr = " SELECT comment_content FROM $wpdb->comments INNER JOIN $wpdb->commentmeta ON meta_key = 'comment_name'";
$comment_info = $wpdb->get_results($querystr, OBJECT);
echo '<ul>';
// display the results
foreach($comment_info as $info) {
echo '<li class="commentBox"><p>'. $info->comment_content .'</p><h6>'. $info->meta_value .'</h6></li>';
}
echo '</ul>';
?>
As you can probably see, I need to get the comment_content field which is in wp_comments, but also combine that with the meta_value of 2 meta_keys. I obviously haven't figured out how to try and add the second meta_key/value to my code.
Can anybody help me please as I am at my wits end with this!
UPDATE:
I can now query the info I need. I had to use aliases so I can query 2 different meta_keys with corresponding values. The code:
$querystr =
" SELECT * FROM $wpdb->comments, $wpdb->commentmeta AS commentmeta1, $wpdb->commentmeta AS commentmeta2
WHERE $wpdb->comments.comment_ID = commentmeta1.comment_id
AND $wpdb->comments.comment_ID = commentmeta2.comment_id
AND commentmeta1.meta_key = 'comment_name'
AND commentmeta2.meta_key = 'comment_country'
ORDER BY $wpdb->comments.comment_date DESC";
$comment_info = $wpdb->get_results($querystr, OBJECT);
So what I now need to do is reference commentmeta1 and commentmeta2 in my loop to output the 2 different values. The code I am using:
echo '<ul>';
// display the results
foreach($comment_info as $info) {
echo '<li class="commentBox"><p>' . $info->comment_content . '</p><h6>' . $info->meta_value['commentmeta1'] . ', ' . $info->meta_value['commentmeta2'] . '</h6></li>';
}
echo '</ul>';
The meta values don't output as they should, it basically takes the first letter only of my commentmeta2 ('comment_country'), and duplicates it for each instance (pic below). If I query only one meta key I can display the value in my loop fine by simply running $info->meta_value. How can I simply my meta_values as per my query?
How about specifying the columns you need in your SELECT statement:
SELECT comment_content, comment_name, comment_country FROM ...
Then reference them in your HTML as $info->comment_name and so on.
If you need more direction, you need to share the database schemas for your comments tables.
Sussed it! Final working code is as follows:
$querystr = " SELECT comment_content, commentmeta1.meta_value AS comment_name, commentmeta2.meta_value AS comment_country
FROM $wpdb->comments, $wpdb->commentmeta AS commentmeta1, $wpdb->commentmeta AS commentmeta2
WHERE $wpdb->comments.comment_ID = commentmeta1.comment_id
AND $wpdb->comments.comment_ID = commentmeta2.comment_id
AND commentmeta1.meta_key = 'comment_name'
AND commentmeta2.meta_key = 'comment_country' ORDER BY $wpdb->comments.comment_date DESC";
$comment_info = $wpdb->get_results($querystr, OBJECT);
echo '<ul>';
// display the results
foreach($comment_info as $info) {
echo '<li class="commentBox"><p>' . $info->comment_content . '</p>
<h6>' . $info->comment_name . ', ' . $info->comment_country . '</h6></li>';
}
echo '</ul>';
I basically needed to pass the alias into SELECT and assign a new alias which I could reference in my loop.

Show the posts under the same category

I am quite new to wordpress and blogging. I am working on a blog portal that has several blogs but they all use common categories that are listed on the main page of the website. The problem is that whichever category I choose on the main page, it shows me the page with exactly same posts.
Here is my code:
<div class="category-holder list-center">
<h5>Kategoriat</h5>
<?php $site_url = get_bloginfo( 'wpurl' ); ?>
<a target="_blank" href="<?php $site_url; ?>/tags/?avain=<?php the_field('cat1'); ?>"><?php the_field('cat1'); ?></a><br/>
<a target="_blank" href="<?php $site_url; ?>/tags/?avain=<?php the_field('cat2'); ?>"><?php the_field('cat2'); ?></a><br/>
<a target="_blank" href="<?php $site_url; ?>/tags/?avain=<?php the_field('cat3'); ?>"><?php the_field('cat3'); ?></a><br/>
<a target="_blank" href="<?php $site_url; ?>/tags/?avain=<?php the_field('cat4'); ?>"><?php the_field('cat4'); ?></a><br/>
<a target="_blank" href="<?php $site_url; ?>/tags/?avain=<?php the_field('cat5'); ?>"><?php the_field('cat5'); ?></a>
</div>
Could you please suggest some PHP function or give me any tip what I should do, where I should look for a solution for this problem?I hope that you understand that I am just a beginner and I would like to learn more about programming.
Thank you in advance!
Update: I also have a functions.php file, the part of the code that might be relevant:
function tag_posts() {
global $wpdb;
$tag = $_GET['avain'];
$taxarr = array();
$postarr = array();
$blogs = $wpdb->get_results( "SELECT blog_id FROM {$wpdb->blogs} WHERE blog_id != {$wpdb->blogid} AND site_id = '{$wpdb->siteid}' AND spam = '0' AND deleted = '0' AND archived = '0'", ARRAY_A);
array_unshift($blogs, 1);
foreach($blogs as $blog) {
$wpdb->set_blog_id($blog[ 'blog_id' ]);
$tax_id = $wpdb->get_var("SELECT term_taxonomy_id FROM $wpdb->term_taxonomy WHERE term_id IN (SELECT term_id FROM $wpdb->terms WHERE name='$tag')");
$post_id = $wpdb->get_results("SELECT object_id FROM $wpdb->term_relationships WHERE term_taxonomy_id = $tax_id");
foreach ($post_id as $id) {
$postarr = $id->object_id;
}
$posts = $wpdb->get_results("SELECT * FROM {$wpdb->prefix}posts WHERE ID IN ($postarr)");
global $post;
foreach ($posts as $post):setup_postdata($post);
'<div class="post"><header class="post-header"><div class="date-holder"><span>'.the_time('F jS, Y').'</span></div>';
''.$post->post_title.'</header>';
'<div class="post-content">'.the_content().'</div></div>';
endforeach;
}
}
Please follow the steps. This may help you.
Create a new menu in Dashboard > Appearance > Menus.
Add categories in to the menu.
Use the function wp_nav_menu() to display the menu.
The category link in the menu displayed will direct you to the corresponding category page.
Please note that the category link direct you to the corresponding category page if and only if there exists category.php page in your themes folder.
Please, take a look at this loop here:
foreach ($post_id as $id) {
$postarr = $id->object_id;
}
$posts = $wpdb->get_results("SELECT * FROM {$wpdb->prefix}posts WHERE ID IN ($postarr)");
It seems to be that the expected value for $postarr at the moment you query for posts is an array having post IDs. However, when you do $postarr = $id->object_id; you are overwriting the variable assigning to it only the last ID in the result set and the result is an integer variable instead of an array.
So I would suggest something like this instead:
foreach ($post_id as $id) {
$postarr[] = $id->object_id;
}
$postsAsCommaSepString = implode( ',', $postarr );
$posts = $wpdb->get_results("SELECT * FROM {$wpdb->prefix}posts WHERE ID IN ($postsAsCommaSepString)");
First we are adding entries to the $postarr, note the brackets:
$postarr[] = $id->object_id;
Then, since we can't use an array variable as if it was a string, we need to create a string as a comma separated list of IDs to use in the SQL IN. For this, we implode the array into a string using commas as separator:
$postsAsCommaSepString = implode( ',', $postarr );
Finally, we use this new string variable in the query:
$posts = $wpdb->get_results("SELECT * FROM {$wpdb->prefix}posts WHERE ID IN ($postsAsCommaSepString)");
This should solve the problem of fetching the same posts every time.
EDIT: Bad query:
There is also a problem in this query:
$blogs = $wpdb->get_results( "SELECT blog_id FROM {$wpdb->blogs} WHERE blog_id != {$wpdb->blogid} AND site_id = '{$wpdb->siteid}' AND spam = '0' AND deleted = '0' AND archived = '0'", ARRAY_A);
In SQL, the not equal operator goes like this <> instead of !=. Please, see the corrected form below:
$blogs = $wpdb->get_results( "SELECT blog_id FROM {$wpdb->blogs} WHERE blog_id <> {$wpdb->blogid} AND site_id = '{$wpdb->siteid}' AND spam = '0' AND deleted = '0' AND archived = '0'", ARRAY_A);

SQL Query function and joining databases

I would like to get all the the corresponding images from one mySQL table that have a corresponding post_ID to the ID of another table.
So with an ID of 7 in table wp_post, I want to echo the values of infomation in another table that has a certain meta_key and a corresponding ID.
===WP_POST=========== ===WP_POSTMETA======================================
ID || content post_id || meta_key || meta_value
================================================================================
The meta_key that I want is listed as _wp_attached_file in the database.
So I want to get all meta_values of wp_postmeta table that have a meta_key of _wp_attached_file and a post_id that matches the current ID of the page being viewed from the table wp_posts.
So obviously the tables will need to be joined but I need a hand.
Any ideas,
Marvellous AHAA
Implemented solution below and I am now receiving an error.
<?php
$pics = mysql_query("SELECT t2.meta_key,t2.meta_value from (select id from wp_post) t1
join wp_postmeta t2 on (t2.post_id=t1.postid)
where t2.meta_key='_wp_attached_file'");
while ($row = mysql_fetch_array($pics)) {
$thumb = $row['meta_value'];
echo '<img src="http://www.golfbrowser.com/wp-content/uploads/'.$thumb.'" />';
}
?>
Any ideas?
I tried a simpler way myself. Still does not work.Can anyone see what is wrong.
<?php
$post_id = $post->ID;
$pics = mysql_query("
SELECT meta_value * FROM wp_postdata
WHERE meta_key ='_wp_attached_file'
AND post_id = '%$post_id%'
");
while ($row = mysql_fetch_array($pics)) {
$thumb = $row['meta_value'];
echo '<img src="http://www.golfbrowser.com/wp-content/uploads/'.$thumb.'" />';
}
?>
Try this query:
SELECT A.meta_key
FROM WP_POSTMETA AS A
JOIN WP_POST AS B
ON (A.post_id = B.ID)
WHERE A.post_id='%post_id%' ;

how to eliminate a particular category from query

I have been presented with this code. The code displays the title headings of the latest 10 WordPress posts from the database. What I need to do is to eliminate a particular category from this. Can anyone help?
<?php require_once 'news/wp-config.php';
$howMany = 0;
$query ="SELECT `ID`, `post_title`,'post_category', `guid`,SUBSTRING_INDEX(`post_content`, ' ', 100) AS `post_excerpt` FROM $wpdb->posts WHERE `post_status`= \"publish\" AND `post_type` = \"post\" ";
$posts = $wpdb->get_results($query);
$posts = array_reverse($posts);
foreach($posts as $post)
{
if($howmany<10)
{
$link = $post->guid;
echo "<li><a target='_blank' href='$link'>$post->post_title</a></li>";
$howmany++;
}
}
?>
Or, you could use a second loop, something like this :
<div>
<h3>Fresh Posts</h3>
<ul>
<?php
$my_query = new WP_Query("cat=-3&order=DESC&posts_per_page=10");
echo "<pre>"; print_r($my_query->query_vars); echo "</pre>"; // shows the variables used to parse the query
echo "<code style='width: 175px;'>"; print_r($my_query->request); echo "</code>"; // shows the parsed query
while ($my_query->have_posts()) : $my_query->the_post(); //standard loop stuff
$do_not_duplicate[] = $post->ID;?>
<li id="post-<?php the_ID(); ?>"><?php the_title(); ?></li>
<?php endwhile; ?>
</ul>
</div>
once again WP 2.8.x. Lots of good info here : WordPress loop documentation
Determine the category you don't need and add an extra AND to your WHERE clause:
AND post_category != 3
You can do it either of 2 places. The most efficient is to do it in the query:
$query ="SELECT ID, post_title, post_category, guid, SUBSTRING_INDEX(post_content, ' ', 100) AS `post_excerpt`
FROM $wpdb->posts
WHERE post_status= 'publish'
AND post_type = 'post'
AND post_category!= 'unwanted string' ";
The other place to do it, if for some reason you need all the results, but you want to use the unwanted category somewhere else, is when you retrieve the results:
if($howmany<10 && post['post_category']!='unwanted string') {
'Noticeboard' is the name of the category i want to eliminate. but if i write that, it dispalys a parse error.
Because you must insert the category ID in the query, not the category name.
To get that, just watch in the database wp_categories table.
Some links about wordpress database:
http://blog.kapish.co.in/2008/01/18/wordpress-database-schema/
http://wpbits.wordpress.com/2007/08/08/a-look-inside-the-wordpress-database/
Anyway, I think it's more hard than this. Look at post2cat table.
So, you have to do a subquery.
I am not sure which WP version you are using, so this 'answer' has a few caveats.
Caveat 1 : This is not a complete answer, more like a pointer
Caveat 2 : The query below works with WP 2.8.x so YMMV
The query below shows how to link posts back to their categories. You can use the NOT IN mySQL operator to exclude the category you do not want by its ID
SELECT
wp_posts.*
FROM
wp_posts
INNER JOIN
wp_term_relationships
ON
(wp_posts.ID = wp_term_relationships.object_id)
INNER JOIN
wp_term_taxonomy
ON
(wp_term_relationships.term_taxonomy_id = wp_term_taxonomy.term_taxonomy_id)
WHERE
wp_term_taxonomy.taxonomy = 'category'
AND
wp_term_taxonomy.term_id NOT IN ('3')
AND
wp_posts.post_type = 'post'
AND
(wp_posts.post_status = 'publish' OR wp_posts.post_status = 'future')
GROUP BY
wp_posts.ID
ORDER BY
wp_posts.post_date
DESC
The line breaks and indenting are idiosyncratic, but (hopefully) make it easier for you to see what is going on with this query.
I hope this helps.

Categories