logo
down
shadow

How to get array value from wordpress database get_results


How to get array value from wordpress database get_results

Content Index :

How to get array value from wordpress database get_results
Tag : php , By : user157138
Date : November 26 2020, 03:01 PM

seems to work fine You have to use the correct syntax $wpdb->get_results( $query, $type_of_result);
check this out here
$users = $wpdb->get_results( "SELECT SUM(wp_wpdatatable_1.payback) as sumed FROM wp_wpdatatable_1", ARRAY_A);

Comments
No Comments Right Now !

Boards Message :
You Must Login Or Sign Up to Add Your Comments .

Share : facebook icon twitter icon

Creating an associative array from Wordpress $wpdb->get_results


Tag : php , By : BinaryBoy
Date : March 29 2020, 07:55 AM
like below fixes the issue It's been a long day and for some reason this is totally eluding me...
$array = array();
foreach ($results as $res){
    $array[] = $res->organisation;
}

Build new custom Array from Wordpress $wpdb->get_results array


Tag : php , By : Morbo
Date : March 29 2020, 07:55 AM
To fix this issue I think what you need to do is break down the process down into steps (so you can change the data around) instead of sending your sql data to json directly.
build your own array iterate over your sql result set while adding your own markup send the output to json
$preJSON = array();    

// select only columns you need
$sql = "SELECT id, gender, country_srt, lat, long
        FROM wp_table"


$count = 0; // this is for $preJSON[] index

foreach( $wpdb->get_results( $sql ) as $key => $row ) {

    // each column in your row will now be accessible like this: 
    // $my_column = $row->column_name;
    // now we can do:

    $value = $row->id;
    $latitude = $row->lat;
    $longitude = $row->long;
    $gender = $row->gender;
    $country = $row->country_srt;
    $tooltip = array(
        "content" => "HTML and stuff" . $gender . "more HTML and stuff" . $country
    );

    // now we can build a row of this information in our master array
    $preJSON[$count] = array(
        "value" => $value,
        "latitude" => $latitude,
        "longitude" => $longitude,
        "tooltip" => $tooltip
    );

    // increment the index
    ++$count;
}

// after foreach
// send the whole array to json
$json = json_encode( $preJSON );

Custom JSON array from Wordpress $wpdb->get_results array


Tag : php , By : Imran
Date : March 29 2020, 07:55 AM
it helps some times A few things:
1) Doing another join with the *_usermeta table is not necessary because WP has functions (such as get_userdata ) that take care of that for you right from the box. I took the liberty to remove it from the QUERY
<?php

// select only columns you need
$sql = $wpdb->prepare("SELECT
      wptest_users.ID,
      wptest_users.display_name,
      wptest_pmpro_memberships_users.user_id,

      FROM
      wptest_users,
      wptest_pmpro_memberships_users,
     WHERE
      wptest_pmpro_memberships_users.membership_id = 1
      AND wptest_pmpro_memberships_users.status = 'active'
      AND wptest_pmpro_memberships_users.user_id = wptest_users.ID");


$count = 0; // this is for $preJSON[] index
$user_object = array();
foreach( $wpdb->get_results( $sql ) as $key => $row ) {
  // "userid" : 3, "name" : THENAMEOFUSER, "usermeta": { "nickname" : "UP", "first_name" : "Nicky" "last_name" : "PH" }
    // each column in your row will now be accessible like this:
    // $my_column = $row->column_name;
    // now we can do:

    $userid = $row->ID;
    // $displayname = $row->display_name;
    // $user_meta = $row->meta_value;
    // $metadata = array(
    //     $row->meta_key => $user_meta
    // );
    $user_info = get_userdata($userid);
    $firstname = $user_info->first_name;
    $lastname = $user_info->last_name;
    $display_name = $user_info->display_name;


    // now we can build a row of this information in our master array
    // $preJSON[$count] = array(
    //     "userid" => $userid,
    //     // "name" => $displayname,
    //     // "usermeta" => $metadata
    // );

    $user_object[$count]= array(
        "userid"=>$userid,
        "name"=>$display_name,
        "usermeta"=>array(
          "nickname" : $display_name,
          "first_name" : $firstname,
          "last_name" : $lastname
        )
      );

    // increment the index
    ++$count;
}

// after foreach
// send the whole array to json
return wp_send_json( $user_object );
?>

Wordpress How to get value from get_results function


Tag : php , By : n3txpert
Date : March 29 2020, 07:55 AM
may help you .
First of all if you want to get only one record then use get_row() instead of get_results() because it will fetch all the data retrieved by SQL query.
$result = $wpdb->get_row("SELECT SUM(view) as dviews FROM view_count WHERE post_id = '$pid'");
echo $result->dviews;
$results = $wpdb->get_results("SELECT SUM(view) as dviews FROM view_count WHERE post_id = '$pid'");
foreach ($results as $result)
{
    echo $result->dviews;
}

Does using the WordPress get_results() database function prevent sql injection


Tag : mysql , By : Sandip
Date : March 29 2020, 07:55 AM
hope this fix your issue Ok so as tadman explained the get_results does not prevent the sql injection attack.
the prepare function needs to be used.
global $wpdb;
$offset = (isset($_POST["moreSearchResults"])) ? $_POST["searchOffset"] : 0;

$querySearchVals = "
    SELECT DISTINCT post_title, ID
    FROM {$wpdb->prefix}posts
    WHERE (";

$sVals = array();
$sVals = explode(" ", $searchVal);

$lastIndex = intval(count($sVals)) - 1;
$orderByCaseVals = "";
for($i = 0; $i<count($sVals);$i++)
{
    $queryPrep = $wpdb->prepare(" post_title LIKE '%%%s%%' ", $wpdb->esc_like( $sVals[$i] ));
    $querySearchVals .= $queryPrep;
    if($i != $lastIndex)
        $querySearchVals .= " OR ";

    $queryPrep = $wpdb->prepare(" WHEN post_title LIKE '%%%s%%' THEN ($i + 2) ", $wpdb->esc_like( $sVals[$i] ));
    $orderByCaseVals .= $queryPrep;
}

$querySearchVals .= ") 
    AND {$wpdb->prefix}posts.post_type = 'post'
    AND post_status = 'publish' 
    ORDER BY CASE";

$queryPrep = $wpdb->prepare(" WHEN post_title LIKE '%%%s%%' THEN 1 ", $wpdb->esc_like( $searchVal ));
$querySearchVals .= $queryPrep;
$querySearchVals .= "
        $orderByCaseVals
    END
";

$queryPrep = $wpdb->prepare(" LIMIT %d, 12", $offset);
$querySearchVals .= $queryPrep . ";";
Related Posts Related QUESTIONS :
  • Assign indexed array values to multidimensional array?
  • Custom WordPress stylesheet not loading
  • Data attribute only returning first value
  • How to list all roles with Permissions,in spatie permission Package?
  • How to achieve this number pattern with n input
  • How to iterate array inside array data in laravel ,output are given below
  • To get output of movie with its genre
  • Extracting some data from a JS object literal string in PHP using Regex
  • axios and vuex are deleting wrong index in array
  • Setting empty CURLOPT_POSTFIELDS
  • Laravel 5.8 use subdomain as API endpoint beside domain.com/api
  • Error while add data in database SQL Server 2016
  • Does PhpStorm allow to skip PHPDoc tags when type hints is declared?
  • html classes are changed to Attributes
  • Using json to import multidimensional data
  • passing data from the view to the controller, where the data comes from another controller
  • How to extract integer and decimal numbers in PHP string correctly?
  • Parsing Sub-Object from an XML Feed with objects
  • Getting error "Unknown column 'text' in 'field list'"
  • How to properly get onedrive access token via php and curl
  • How to add spell check to a php function
  • Is it posible to create css rules with php?
  • Pretty URL with $_GET method
  • Wordpress always load same page - index.php
  • Find value in array and return with new from different array
  • PHP multiple file upload with different keys
  • Can't modify times one a time without weird errors
  • Get size of scraped image with domcrawler (Goutte)
  • Laravel - Ordering a collection of models
  • PHP Fatal error: Uncaught Error: Call to a member function setFetchMode() on boolean
  • Strict Standards: Only variables should be passed by reference in /main_dir/sub_dir/backup.php
  • Uncaught Google_Exception: (update) unknown parameter: 'copyRequiresWriterPermission'
  • Laravel 5 form does not redirect with old input
  • How to get values greater than or equal to in Mysql database sql when its a value like 1:00 PM?
  • PHP datediff overday issue
  • Masking an auto incrementing primary key
  • How to grab a String BEFORE a certain word
  • ZF2 Routing Multiple Controllers based on route constraints
  • How to deregister/dequeue jquery.sticky.js in Elementor (Pro)?
  • How to fix errors counting words in text plain with PHP?
  • How to get View data in Laravel in custom helper or directive
  • Creating a new data entry into a database with eloquent and trying to access the variable in the url
  • How to test authentication using Laravel Dusk?
  • PHP parse_str not getting all $_GET variables
  • Variable issues in php class
  • Get orders between dates in Codeigniter
  • Eloquent Special Chars Issue
  • Keeping leading zeros column Mysql
  • Current level navigation in Wordpress
  • Add a custom text to WooCommerce cart items if the product has a specific shipping class
  • Error connecting to CommissionJunction Token : [60] SSL certificate problem: unable to get local issuer certificate
  • How do I add a new key value pair to an object in PHP?
  • Http post request to php with dart
  • How to add a route in with blade into parameters of a component
  • How can i get the source of a 777 - CHMOD php file?
  • Convert 2010-04-16 16:30:00 to "Tomorrow Afternoon"
  • How can I hide a $_GET variable to be more secured in PHP?
  • Login to Gmail Inbox using Curl?
  • Upload Excel or CSV file to MySQL with PHP
  • Outlook Marking Email as Junk Email
  • shadow
    Privacy Policy - Terms - Contact Us © scrbit.com