Stumped on this little SQL query - sql

This SQL query is currently returning all values with the word anywhere in it. For instance, typing Mon will return Armoring, Behemoth, Emotion, etc etc. I'd like it to return words that start with the value, like, Monkey, Moment, Monday, etc.
Hope my explanation makes sense, code is below.
function action_ajax_drug_suggest() {
global $wpdb;
if ( empty( $_GET['term'] ) ) {
die();
}
$drug_name = $wpdb->esc_like( $_GET['term'] );
$table = $wpdb->prefix . self::TABLE_DRUG;
$posts = $wpdb->get_results( $wpdb->prepare( "
SELECT name
FROM {$table}
WHERE name LIKE '%%%s%%'
AND details <> ''
LIMIT 5",
$drug_name ) );
foreach( $posts as $post ) {
$names[] = array(
'label' => $post->name,
);
}
wp_send_json( $names );
}

try leaving out the first two %% signs
LIKE '%%%s%%' becomes LIKE '%s%%'

Related

validating the elementor form field data in mysql DB in wordpress

I'm trying to verify the file number whether it exist in Database or not if it exists it give success message, if not then show invalid number. My Tab has only one col i.e fileNumber. This is the code I have tried to put in the child theme in functions.php. when I enter the file number in the name field this code only show the statement after else statement ($ajax_handler->add_error( $field['id'], 'Invalid number' );). is there any other way to do this?
here is the code
add_action( 'elementor_pro/forms/validation', function ( $record, $ajax_handler ) {
$fields = $record->get_field( ['id' => 'name1',] );
if ( empty( $fields ) ) {
echo "enter the file number";
}
$field = current( $fields );
global $wpdb;
if($wpdb->connect_error){
echo 'Connection Failed: ';
}
$sql = $wpdb->get_results( "select fileNumber from wpbd_FileNumbers where fileNumber like '%$field%'");
/* $sql="select * from $wpdb->wp_FileNumbers where fileNumber like '%$field%'";*/
if($sql == $field){
$ajax_handler->add_response_data( true, $output );
}
else
$ajax_handler->add_error( $field['id'], 'Invalid number' );
}, 10, 2);

posts_orderby not displaying the posts

I would like to customize my wordpress search page
First, i used the "posts_where" to modify the clause
function search_posts_where ($where) {
global $wp_query, $wpdb;
// Searching and not in admin
if (!is_admin() && $wp_query->is_search && isset($wp_query->query_vars['s'])) {
// Tables names
$post_title = "{$wpdb->prefix}posts.post_title";
$post_excerpt = "{$wpdb->prefix}posts.post_excerpt";
$post_content = "{$wpdb->prefix}posts.post_content";
$post_type = "{$wpdb->prefix}posts.post_type";
$post_status = "{$wpdb->prefix}posts.post_status";
$post_author = "{$wpdb->prefix}posts.post_author";
$post_ID = "{$wpdb->prefix}posts.ID";
$post_date = "{$wpdb->prefix}posts.post_date";
// Get the 's' parameters
$wp_query->query_vars['s'] ? $search_text = $wp_query->query_vars['s'] : $search_text = 'IS NULL';
// Write the where clause
$where = " AND ((($post_title LIKE '%$search_text%')";
$where .= " OR ($post_excerpt LIKE '%$search_text%')";
$where .= " OR ($post_content LIKE '%$search_text%')))";
$where .= " AND $post_type IN ('parcours')";
$where .= " AND $post_status = 'publish'";
$where .= " GROUP BY $post_ID";
}
return $where;
}
add_filter('posts_where', 'search_posts_where', 10, 2);
It works fine. All posts belonging to my custom post type 'parcours' are shown, depending on what I entered for the 's' query.
Second, i used the "posts_join" to add the meta table (not used yet !)
function search_posts_join ($join) {
global $wp_query, $wpdb;
// Searching and not in admin
if (!is_admin() && $wp_query->is_search && isset($wp_query->query_vars['s'])) {
// Tables names
$post_meta = "{$wpdb->prefix}postmeta";
$post_ID = "{$wpdb->prefix}posts.ID";
$post_meta_ID = "{$wpdb->prefix}postmeta.post_id";
// Join clause
$join .= "LEFT JOIN $post_meta ON ($post_ID = $post_meta_ID)";
}
return $join;
}
add_filter('posts_join', 'search_posts_join', 10, 2);
Still works perfectly !
Now the problem, i would like to order my posts in ascending direction (default is descending). So, i added the "posts_orderby" hook.
function search_posts_orderby ($orderby) {
global $wp_query, $wpdb;
// Searching and not in admin
if (!is_admin() && $wp_query->is_search) {
// Tables names
$post_title = "{$wpdb->prefix}posts.post_title";
$post_date = "{$wpdb->prefix}posts.post_date";
$post_ID = "{$wpdb->prefix}posts.ID";
// Order by clause
$orderby .= " ORDER BY $post_title ASC,";
$orderby .= " $post_date DESC";
}
return $orderby;
}
add_filter('posts_orderby', 'search_posts_orderby', 10, 2);
And here is the problem. All posts disapeared. Removing the "orderby" and they come back.
Looking at the SQL query, i have
"SELECT SQL_CALC_FOUND_ROWS wp_128444_posts.* FROM wp_128444_posts LEFT JOIN wp_128444_postmeta ON (wp_128444_posts.ID = wp_128444_postmeta.post_id) WHERE 1=1 AND (((wp_128444_posts.post_title LIKE '%tour%') OR (wp_128444_posts.post_excerpt LIKE '%tour%') OR (wp_128444_posts.post_content LIKE '%tour%'))) AND wp_128444_posts.post_type IN ('parcours') AND wp_128444_posts.post_status = 'publish' GROUP BY wp_128444_posts.ID ORDER BY wp_128444_posts.post_title LIKE '{5a35f6e9144541f93e08829126b2cb633436cebf95d774062fff749a12e6a465}tour{5a35f6e9144541f93e08829126b2cb633436cebf95d774062fff749a12e6a465}' DESC, wp_128444_posts.post_date DESC ORDER BY wp_128444_posts.post_title ASC, wp_128444_posts.post_date DESC LIMIT 0, 6"
I don't know why WP is adding the default ORDER BY, that i don't want.
Is is possible to remove it ?
I tried to replace my hook with "pre_get_posts" hook
function order_posts_by_title( $query ) {
if ( $query->is_search() && $query->is_main_query() ) {
$query->set( 'orderby', 'title' );
$query->set( 'order', 'ASC' );
}
}
add_action( 'pre_get_posts', 'order_posts_by_title' );
With this hook, it works !! Sounds very strange to me
Any explanation ?
Thanks

Wordpress Custom Post Type Sort by Title Last Word ASC

I am taking a custom post type and trying to display it by the last word of the post title. From there, I want to pass in a variable of what letter I would like to see (eg "starts_with" = "A") in the WP_Query. Lastly, I want to display this in ASC order. From this code, how do I display in ASC order?
function dp_posts_where( $where, $query ) {
global $wpdb;
$starts_with = $query->get( 'starts_with' );
if ( $starts_with ) {
$last_name = "RIGHT($wpdb->posts.post_title, LOCATE(' ', REVERSE($wpdb->posts.post_title)) - 1)";
$where .= " AND $last_name LIKE '$starts_with%'";
}
return $where;
}
add_filter( 'posts_where', 'dp_posts_where', 10, 2 );
Please advise! Thank you!

Is there a find and replace functions for SQL

I have some values in my SQL i want to trim and replace.
I want to look in a key field _booking_persons and only store all between "" and remove the rest.
So at the moment i got this in all fields
s:14:"a:1:{i:0;i:4;}“
and i want to keep a:1:{i:0;i:4;} so everything between " ".
I tried to fix it with wordpress post_meta_update. So i tought maybe its easy to do that with SQL.
$args = array('post_type' => 'wc_booking', 'posts_per_page' => '-1' );
$the_query = new WP_Query( $args );
// The Loop
if ( $the_query->have_posts() ) {
while ( $the_query->have_posts() ) {
$the_query->the_post();
$post_id = get_the_ID();
$array = get_post_meta( $post_id, '_booking_persons', true );
$between = preg_replace('/(.*)"(.*)"(.*)/sm', '\2', $array);
update_post_meta( $post_id, '_booking_persons', $between );
}
/* Restore original Post Data */
wp_reset_postdata();
} else {
// no posts found
}
I expect a:1:{i:0;i:4;} but stay as it is s:14:"a:1:{i:0;i:4;}“
You can do this easily with substring_index function:
SELECT substring_index(substring_index('s:14:\"a:1:{i:0;i:4;}\"', '\"', 2), '\"', -1);
This will return:
a:1:{i:0;i:4;}
Note that you need to escape " character with \
You can see this in action here

Inserting 2D Values of Array into SQL

Right now, I have looped a form which in the end gives me a 2D Array.
Array 0D
User Arrays 1D
User Fields 2D
Array ( [1] => Array ( [fname] => qweqwe [lname] => qwewqe [email] => qwewqe [age] => wewqe ) [2] => Array ( [fname] => 123123 [lname] => 123123 [email] => 23123 [age] => 23123 ) )
This is an example of what I get when I type in rubbish into my fields.
To check if I could get the values for each form, I used this:
$i = $_POST['number'];
$corporate = $_POST['corporate'];
$x = 1;
print_r($corporate);
while($x <= $i)
{
echo "The first name first name".$corporate[$x]["fname"].".";
}
Using this, I would attain the first name of the first user, followed by the second and so on. This proves that I can get the 2D values from my forms.
What I have to do now is to insert those values into my table. Keep in mind, my 1D contains values of each user. 2D is the values itself.
mysql_query("INSERT INTO students ('fname','lname','email', 'age') VALUES
I have no idea what to put after that. Any help would be appreciated.
You need to add a set of data values to insert. These would be in the form ("Robert","Brown","Robert.Brown#uni.com","34")("Robert","Smith","Robert.Smith#uni.com","33")
What version of PHP are you using?
for php5.3 you could try:
$values = array();
foreach($corporate as $line){
$values[] = "('".implode("','",array_map(function($x){ return addslashes($x); })) . "')";
}
$query = "INSERT INTO students ('fname','lname','email', 'age') VALUES";
$query .= implode($values);
$record = mysql_query($query);
Otherwise, try:
$values = array();
foreach($corporate as $line){
foreach($line as $i=>$item) $line[$i] = addslashes($item);
$values[] = "('".implode("','",$line) . "')";
}
$query = "INSERT INTO students ('fname','lname','email', 'age') VALUES";
$query .= implode($values);
$record = mysql_query($query);
To solve the second part of your problem, you need to edit the table definitions and remove the "NOT NULL" definition that sits on each field. Do you have php my admin on the server? you could do it through that by editing the table and fields, otherwise you could run the sql using ALTER TABLE. Let me know if you want more information on that.
Well, using your query, understanding what it means in depth, I finally got it working.
This is the code that I used:
foreach($corporate as $line)
{
$values[] = "('".implode("','",$line) . "')";
echo "<br />";
print_r($values);
$a = implode(",", $values);
echo $a;
}
$query = "INSERT into students (fname, lname,email,age) VALUES $a";
$sql = mysql_query($query);
This works fine on my database, works like a charm.
However, when I try this on my friends DB or an Online DB, I get an error which requires me to give every field a value. For some reason, it cannot enter NULL values.
I'm trying to figure out why, but the gist of my problem has been solved.
If you know what is causing my error, feel free to comment. Thanks.