php wordpress - retrieveing values from mysql table one by one - php

I have been trying to retrieve data one by one from mysql table that I just created. Below Image has shown the table that includes the sample coupon codes and a field called "test" to specify if the code has been generated by users.
My goal is to retrieve coupon codes below "adidas" serially (arda10, arda11, arda12,...) and update the status of the coupon in test column after the coupon code is shown.
If the status in test column is 1, the code should not be shown to the users. Only codes with status 0 should be printed.
$kupon = $wpdb->get_results( 'SELECT * FROM `wp_kuponlar`', ARRAY_A);
echo $kupon[adidas];
Help please!

Am not sure what your question and what the error might be, but this is a better formating and way to go please ensure you adidas is qouted like the example I have below.
$kupon = $wpdb->get_results( 'SELECT * FROM wp_kuponlar', ARRAY_A);
foreach($kupon as $coupon){
echo $coupon['adidas'];
}
Extra tip
if the table is attached to wordpress db and not a totally different db, the better way to go is doing the following
$kupon = $wpdb->get_results( "SELECT * FROM {$wpdb->prefix}_kuponlar", ARRAY_A);
Based on Comment
$kupon = $wpdb->get_results( "SELECT * FROM {$wpdb->prefix}_kuponlar where status = 0 Orderby id ASC", ARRAY_A);
foreach($kupon as $coupon){
echo $coupon['adidas'];
}

Get results from wp database table use $wpdb->get_results() query something like this,
It gives you all your data with test status 0 or 1
<?php
global $wpdb;
$kupon = $wpdb->get_results(
$wpdb->prepare(
'SELECT * FROM wp_kuponlar'
), ARRAY_A
);
foreach ($kupon as $coupon) {
echo $coupon['adidas'];
}
but if you want to filter values for 0 only the change query as,
<?php
global $wpdb;
$kupon = $wpdb->get_results(
$wpdb->prepare(
'SELECT * FROM wp_kuponlar WHERE test = %d', 0
), ARRAY_A
);
foreach ($kupon as $coupon) {
echo $coupon['adidas'];
}
Find the result data set in order of coupons in ascending order with test status not 1,
<?php
global $wpdb;
$kupon = $wpdb->get_results(
$wpdb->prepare(
'SELECT * FROM wp_kuponlar WHERE test != 1 ORDER BY RIGHT(adidas,3)'
), ARRAY_A
);
// Now the resultset will be in order of ids
foreach ($kupon as $coupon) {
echo $coupon['adidas'];
}

Related

Update all WooCommerce product prices to 2 decimals in database

Many of my products have prices like £3.4560 etc. I need them to rounded and stripped to just 2 in the database.
The output of 2 decimal places in WooCommerce is not enough and fails to work with a Tax Toggle plugin.
Is there a database query that can do this?
I've seen some bits on Rounding and Truncate but not sure how to execute this as my knowledge is poor.
Any help is appreciated.
Update 2: (Added some code to clear all related product transient cache)
Here is some code that will update all the product prices (make a database backup before):
global $wpdb;
$postmeta = $wpdb->prefix . "postmeta";
$posts = $wpdb->prefix . "posts";
// 1. First query: Get all prices
$results = $wpdb->get_results( "
SELECT $postmeta.*
FROM $postmeta
INNER JOIN $posts ON $postmeta.post_id = $posts.ID
WHERE $posts.post_type LIKE '%product%'
AND $postmeta.meta_key LIKE '%price%'
AND $postmeta.meta_value != ''
ORDER BY $postmeta.meta_id ASC
" );
// iterating through each price and update it
foreach($results as $result){
$meta_id = $result->meta_id;
$post_id = $result->post_id;
$meta_key = $result->meta_key;
$meta_value = number_format( $result->meta_value, 2 );
// 2. Udating prices query
$wpdb->query( $wpdb->prepare( "
UPDATE $postmeta
SET meta_id = $meta_id, post_id = $post_id, meta_key = '$meta_key', meta_value = '$meta_value'
WHERE $postmeta.meta_id = %d
", $meta_id ) );
// 3. Clear all related product transient cached data (refresh prices)
wc_delete_product_transients($post_id);
}
Code goes in function.php file of your active child theme (or theme) or also in any plugin file.
Once saved, just browse any page of your site, check your database wp_postmeta table searching for ‰price‰ LIKE meta_key. Now you can remove this code.

Multiple MySQL queries on one page (WordPress)

I am currently running the following query on my WordPress website:
PHP:
function get_details($key, $post_id) {
global $wpdb;
$values = $wpdb->get_results( "SELECT meta_value FROM {$wpdb->prefix}new_post_meta WHERE meta_key = '{$key}' AND post_id = '{$post_id}' LIMIT 1" );
return $values[0]->meta_value;
}
ON PAGE:
<?php echo get_details('facebook_url', $post_id); ?>
It is a new custom table which works in the same way as the WP posts meta.
This is run 20 + times on the page so I was wondering if there's a better way to do this?
Currently running the query direct in the database it takes 0.5128 sec and the database table is 36MB in size.
The query is really slowing the site down.
Thanks to shadow for stating the obvious but it worked:
public function get_meta_data() {
$meta_keys = array(
//META KEYS GO HERE IN ARRAY
);
$mks = implode("', '", $meta_keys);
//Get Results
global $wpdb;
$results = $wpdb->get_results( "SELECT meta_key, meta_value FROM {$wpdb->prefix}resorts_meta WHERE meta_key IN ('{$mks}') AND post_id = '{$this->id}'", OBJECT_K );
foreach($results as $key => $value) {
$this->$key = $value->meta_value;
}
return "SELECT meta_key, meta_value FROM {$wpdb->prefix}new_post_meta WHERE meta_key IN ('{$mks}') AND post_id = '{$this->id}'";
I then created a function to display the results in $this->variables like so:
public function get_meta( $key ) {
return $this->$key;
}
And then stored get_meta_data in the construct function.
Thanks Shadow.

Getting a single MYSQL result where the field is an array

Wordpress database, bit stuck on this one.
I'm using the following to get the ID of the current user.
$user_ID = get_current_user_id();
This returns something like this :
15
Now I try to find the matching value of $user_ID in the field show_user_list The data in this field is stored in an array.
Which looks something like this :
a:2:{i:0;s:2:"29";i:1;s:2:"15";}
This is the query i'm running (along with a set of conditions) :
global $wpdb; $result = $wpdb->get_results( "SELECT post_id FROM wp_postmeta WHERE show_user_list IN (' . implode(',', $user_ID) . ' AND post_type = 'show' AND post_status = 'publish'" );
And then I'm trying to echo the value of the matching post_id with this :
foreach ( $result as $unique ) {
echo $unique->post_id;
}
But it's not returning anything. I know I must be making a mistake while dealing with the array but I don't know where I'm going wrong?
looks like you have stored a serialized array in the show_user_list field, so it will be a hustle to search for values into using a db query.
In the model you described, you have to select all the rows from wp_postmeta that match "post_type = 'show' AND post_status = 'publish'", then manually filter results that do not have the user id in the unserialized show_user_list field.
You might try something like :
in_array($user_ID, unserialize($row->show_user_list))
Also, I noticed multiple errors in your query: string not properly concatenated with PHP code and the right parenthesis of the IN clause not closed.
Regards,
same
EDIT
Here is how I would solve your problem providing info you have given :
$user_ID = get_current_user_id();
global $wpdb;
$results = $wpdb->get_results("SELECT post_id, show_user_list FROM wp_postmeta WHERE post_type = 'show' AND post_status = 'publish'");
$user_post_ids = array();
foreach ($results as $post) {
if (in_array($user_ID, unserialize($post->show_user_list))) {
$user_post_ids[] = $post->post_id;
}
}
Hope this helps !

how to keep value result query but outside looping foreach

this is my code
global $wpdb;
foreach( $wpdb->get_results("SELECT * FROM detail_buyer ORDER BY id DESC LIMIT 1") as $key => $row)
{
$barang=$row->nama_barang;
//in this table field 'nama_barang' have values more than one
}
echo $barang;
but output result look like this
tempe
any idea how I could do this?
Remove the LIMIT in your query,
SELECT * FROM detail_buyer ORDER BY id DESC
For keep your results of values, you need to create an array variable and store into them.
like this
$barang[] =$row->nama_barang;
Try this,
global $wpdb;
foreach( $wpdb->get_results("SELECT * FROM detail_buyer ORDER BY id DESC LIMIT 1")
as $key => $row)
{
$barang[] =$row->nama_barang; // changes made here
//in this table field 'nama_barang' have values more than one
}
print_r($barang);
Change your code to this :
global $wpdb;
$results = $wpdb->get_results("SELECT * FROM detail_buyer ORDER BY id DESC");
$barang = array();
foreach( $results as $key => $row)
{
$barang[] = $row->nama_barang;
//in this table field 'nama_barang' have values more than one
}
echo implode(', ', $barang);
I've deleted the LIMIT 1 witch was limiting your request to 1 result.
PS : Never put your query directly in your loop instruction.
Edit : For more explanation, I replace your variable by an array, I keep each value in it, and at the end I show our array as a string (using ', ' as separator).

WordPress custom SQL

I have this function which contains some custom SQL:
function user_comment_count_by_meta( $user_id, $meta_key )
{
global $wpdb;
$count = 0;
$sql = "SELECT count(*) FROM $wpdb->comments comments INNER JOIN $wpdb->commentmeta meta ON comments.comment_ID = meta.comment_id WHERE comments.user_id = %d AND meta.meta_key = %s";
$count = $wpdb->get_var( $wpdb->prepare( $sql, $user_id, $meta_key ) );
return $count;
}
What it should be doing is counting all the comments for a user that have a particular meta value attached to them and returning that number. So for example if a user has made 20 comments and then 11 of those have the meta value 'accepted' attached to them then the number returned would be 11.
I call the function like so:
<?php $count = user_comment_count_by_meta( get_the_author_meta('id'), 'accepted' ); ?>
However it doesn't return anything. Not sure where I have gone wrong? If any SQL geniuses could help or if anyone can spot a problem it'd be much appreciated. Thanks.
Well,I think that the SQL it's ok, but when you call your function you are using
get_the_author_meta('id')
and this function I think that have other meaning.
If you want the ID from the post author you must use:
get_the_author_ID()
I'm not sure. really.

Categories