How can I grab data from all of the matching fields? - php

What is the propper syntax to grab data from all of the matching fields?
This example outputs only 1 of the matching fields:
$myvariable = "SELECT post_content
FROM wp_posts
WHERE post_name = 'testing'
AND post_status = 'publish'
AND post_type = 'post'";
echo = $myvariable;

You need to fetch an array of that query:
<?php
$query = mysql_query("SELECT post_content FROM wp_posts WHERE post_name = 'testing' AND post_status = 'publish' AND post_type = 'post'");
while($result = mysql_fetch_array($query)){
echo $result['post_content'];
}
?>
That will loop through the result list from the query and echo the post_content field value.
EDIT: Wow... Same thing, a few seconds late. Ha!

Your question is not clear to me. There may be two cases:
You want to get all the rows which match you condition.
then you should use a loop to grab all matching records as below:
$result = mysql_query("SELECT post_content FROM wp_posts WHERE post_name = 'testing' AND post_status = 'publish' AND post_type = 'post'");
if(mysql_num_rows($result)>0)
while($row = mysql_fetch_assoc($result)){
echo $row['post_content'];
}
I couldn't understand what you want to know. If you want to select all the fields of selecting row then use:
SELECT * FROM wp_posts WHERE post_name = 'testing' AND post_status = 'publish' AND post_type = 'post'
OR
SELECT col1,col2,...,coln FROM wp_posts WHERE post_name = 'testing' AND post_status = 'publish' AND post_type = 'post'
If you want to check conditions with all the fields then you are on the right track, just compare each value with its respective column.

list all the fields in your select statement or use * to select all.
$myvariable = "SELECT * FROM wp_posts WHERE post_name = 'testing' AND post_status = 'publish' AND post_type = 'post'"

You'll need to pull out the query and run a loop over the result rows that come back.
$query = mysql_query("SELECT post_content FROM wp_posts
WHERE post_name='testing'
AND post_status='publish' AND post_type = 'post'");
You'll need to adjust the above query to whichever rows you want to display as well as whatever criteria you want to match against.
And then run something like a while loop with each pass of the rows that were returned:
while($result = mysql_fetch_array($query))
{
echo $result["post_content"];
}
The above will go and pull out all the rows one by one that matched your query and display them however you style it.

If you want to match any, then your SQL is false.
SELECT post_content FROM wp_posts WHERE post_name = 'testing' OR post_status = 'publish' OR post_type = 'post'
The query above finds each record which contains exactly one of the search strings.
But if you want to find it within a sentence then you better use the MATCH function.
MySQL Full-Text Search Functions

Related

Wordpress Mysql query to replace empty alt img with post_title

I have several empty img alt on my wordpress site (about 3k).
After considering different solutions, looks like the best approach is to do a replace on the database.
I would like to replace empty alt in post_content (alt="") with post_title (alt="This is the post title").
Something like that:
update wp_posts
set post_content = REPLACE(post_content,'alt=""', 'alt=" + post_title + "')
where post_status = 'publish';
But I don't get how to insert the post_title value in the query.
Thank you for your help
use a query like this:
UPDATE wp_posts
set post_content =
REPLACE(post_content,'alt=""', CONCAT('alt="', post_title, '"'))
WHERE post_status = 'publish';
and for a specific lenght use SUBSTRING()
UPDATE wp_posts
set post_content =
REPLACE(post_content,'alt=""', CONCAT('alt="', SUBSTRING(post_title,1,20), '"'))
WHERE post_status = 'publish';

Getting 'meta_value' when searching for matching 'post_id' and 'meta_key', 'meta_value' combo

postmeta table example
The end result is matching an array of 'post_id', sorted by the number of attendees. I know it is a WP backend but I have to do it in SQL, no 'get_posts' or anything WordPress related. What I'm wanting to do is confusing so I'll try to be clear.
What I Have To Begin:
$check_post_ids - the original array of post_ids I need to check
$start_date - the 'meta_value' each event's '_StartDate' needs to match.
What I Need To Do:
I need to check these three post_ids to see if they have a matching start date. If they do, I need to get an array of post_ids sorted from the highest to lowest number of attendees.
Currently I was planning on doing this with multiple SELECTs and foreach() statements, but I feel like there has to be a simpler way to do this ( i.e. One SELECT & foreach() ). Here's what I'm doing at the moment. I haven't finished it yet because I feel like there has to be a simpler way to do this. Newer to SQL and any help is tremendously appreciated!
$check_post_ids = array('484', '627', '982', '2435');
$start_date = '1963-10-20 19:30:00';
// iterate through array of post_ids and check if they have the same _StartDate
foreach($check_post_ids as $id){
$start_date_check = "SELECT * FROM `wp_postmeta` WHERE `post_id` =" . $id . " AND `meta_key` LIKE '_StartDate' AND `meta_value` = '" . $start_date . "'";
$start_date_check_result = mysqli_query($conn, $start_date_check);
// assign all post_ids with a matching _StartTime to a new array
if (mysqli_num_rows($start_date_check_result) > 0) {
while($row = mysqli_fetch_assoc($start_date_check_result)) {
$matching_post_ids[] = $row['post_id'];
// iterate through matching_post_ids array, get the _NumAttendees for each, and assign their id and _NumAttendees to an assoc array to be sorted
foreach($matching_post_ids as $id){
$attendees_check = "SELECT meta_value FROM wp_postmeta WHERE post_id = " . $id . " AND meta_key = '_ecp_custom_2'";
$attendees_check_result = mysqli_query($conn, $attendees_check);
if($upvotes_check > 0){
while($row = mysqli_fetch_assoc($attendees_check_result)){
$sort_by_attendees['id'] = $id;
$sort_by_attendees['attendees'] = $row['meta_value'];
$sort_by_attendees_array[] = $sort_by_attendees;
}
}
}
For the first part of the query, I think you can simplify your code by using SQL IN keyword. Basically it substitutes the role of your first array with all your post IDs. Then, you can write a SQL query like this :
SELECT meta_value
FROM wp_postmeta
WHERE meta_key = '_ecp_custom_2'
AND post_id IN (SELECT post_id
FROM wp_postmeta
WHERE post_id IN ('484', '627', '982', '2435')
AND meta_key LIKE '_StartDate'
AND meta_value = '" . $start_date . "'")
ORDER BY meta_value DESC
There are 2 queries. The first one in the parenthesis, subselect all the post ids on your table wp_postmeta where post_ids have ids in your list and if they match with your starting date. Then, the main query selects all meta_values (I suppose attendees) based on your first subquery (all post ids with your starting date).
Hope it will help you.

Search from all custom-fields very slow. I need filter search for custom post type

I'm doing a custom search in my WP and in the search field, any typed word will be sought in custom-fields, in the titles and posting content.
It turns out that my database has more than 1 million custom-fields lines, and wanted to limit the search only for a certain type of post.
I already do this in the Loop to display the results, but I wish this filter was made in consultation because the page is taking over 20 seconds to display the result.
Can anyone help me? Below the code I'm using.
// SEARCH FROM ALL CUSTOM FIELDS
$post_ids_meta = $wpdb->get_col( $wpdb->prepare( "
ALTER TABLE wp_posts ADD INDEX (postmeta)
SELECT DISTINCT post_id FROM {$wpdb->postmeta}
WHERE meta_value LIKE '%s'
", $keyword ) );
// SEARCH FOR TITLE AND CONTENT
$post_ids_post = $wpdb->get_col( $wpdb->prepare( "
ALTER TABLE wp_post s ADD INDEX (posts);
SELECT DISTINCT ID FROM {$wpdb->posts}
WHERE post_title LIKE '%s'
OR post_content LIKE '%s'
", $keyword, $keyword ) );
$post_ids = array_merge( $post_ids_meta, $post_ids_post );
UPDATE:
Try this one. It's not tested but I'm sure it will work if you check and fix it a little bit:
// SEARCH IN title, content and meta_value
$post_ids = $wpdb->get_col( $wpdb->prepare( "
SELECT DISTINCT ID FROM {$wpdb->posts} AS p,
LEFT JOIN {$wpdb->postmeta} AS m,
ON m.post_id = p.ID
WHERE p.post_type = '%s'
AND (
post_title LIKE '%%s%'
OR m.meta_value LIKE '%%s%'
OR post_content LIKE '%%s%')
", $post_type, $keyword, $keyword, $keyword) );
Note:
Assume you have taken input $post_type & $keyword. Eg: $post_type = "fairs";
I added % before and after %s to make sure it's widecard search.
In this case, I use DISTINCT because the joint table have repeated IDs. My apologies for the previous fault assumption on your first query that it was not needed.
Speed is not guaranteed, since you are doing a widecard search on post_content which is not indexed.
You should make sure the meta_value field is indexed for a little faster speed. If you meta don't store too much text in it.
GOOD LUCK!
ORIGINAL:
Firstly, let's clarify these:
Remove these 2 lines as it won't help (it make it worse due to repeated call):
ALTER TABLE wp_posts ADD INDEX (postmeta)
And
ALTER TABLE wp_posts ADD INDEX (posts);
ID is already distinct. So it won't help you do: SELECT DISTINCT ID
The final queries should look like these:
// SEARCH FROM ALL CUSTOM FIELDS
$post_ids_meta = $wpdb->get_col( $wpdb->prepare( "
SELECT post_id FROM {$wpdb->postmeta}
WHERE meta_value LIKE '%s'
", $keyword ) );
// SEARCH FOR TITLE AND CONTENT
$post_ids_post = $wpdb->get_col( $wpdb->prepare( "
SELECT ID FROM {$wpdb->posts}
WHERE post_title LIKE '%s'
OR post_content LIKE '%s' // Remove this will boost performance by 90% because post_content is not indexed
", $keyword, $keyword ) );
$post_ids = array_merge( $post_ids_meta, $post_ids_post );
What I recommend is to use this plugin: https://wordpress.org/plugins/search-everything/
Assuming that $keyword has no wildcards, you might try expressing this query as:
SELECT ID
FROM {$wpdb->posts}
WHERE post_title LIKE '%s'
UNION
SELECT ID
FROM {$wpdb->posts}
WHERE post_content LIKE '%s';
MySQL might figure out to use the indexes for this. The indexes that you want are:
create index wp_post_title_id on wp_post(post_title, id);
create index wp_post_content_id on wp_post(post_content, id);
This assumes that{$wpdb->posts} is really wp_post.

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

PHP take id's from one table and pull data that corresponds with those id's from another table

I have this query:
$query = "SELECT *FROM wp_postmeta WHERE meta_key = '_isEvent' AND meta_value ='yes' ORDER BY post_id LIMIT 0, 5" or die(mysql_error());
$result = mysql_query($query) or die(mysql_error());
while ($row = mysql_fetch_array($result)) {
$eventid = $row ['post_id'];
echo "<p>".$eventid."</p>";
}
This currently posts some ids $eventid. I now want to run another query in another table (same database) that pulls some post titles that matches those id's.
Table is called "wp_posts" and column to match is "ID" and want to echo out post title from "post_title".
Where do I start?
Sounds like you want to use SQL joins. W3 schools has a good intro article about this.
http://www.w3schools.com/sql/sql_join.asp
Something like the following
SELECT post_title FROM wp_postmeta m, wp_posts p WHERE m.wmeta_key = '_isEvent' AND m.meta_value ='yes' AND m.post_id == p.post_idORDER BY m.post_id LIMIT 0, 5

Categories