简体   繁体   English

使用 MYSQL 查询创建 PHP 全局变量

[英]Make PHP global variable using a MYSQL query

I am trying to use a query in WP as a Global variable ( yes I know to avoid those if possible, but This is a query I am going to reference over and over so to me it makes more sense then writing out the same query with each function).我正在尝试将 WP 中的查询用作全局变量(是的,我知道尽可能避免使用这些查询,但这是一个我将一遍又一遍地引用的查询,所以对我来说,用它写出相同的查询更有意义每个功能)。 I must be missing something because the global variable doesn't seem to be working.我一定遗漏了一些东西,因为全局变量似乎不起作用。 How I defined the variable:我如何定义变量:

    $query =  $wpdb->get_results("SELECT columnn1, column2 FROM mytablename");

function query() {
  global $query;
        return $query;
    };

Then when referencing it in a function later I used:然后当我后来在 function 中引用它时,我使用了:

fucntion xyz{
    $results = $query;
//does things
}

Have I done something wrong?我做错了什么吗? It isn't working.它不工作。

EDIT 1:编辑1:

   $query =  $wpdb->get_results("SELECT columnn1, column2

FROM mytablename");

function query() {
  global $query;
        return $query;
    };

Then when referencing it in a function later I used:然后当我后来在 function 中引用它时,我使用了:

fucntion xyz{
global $query
    $results = $query;
//does things
}

try this尝试这个

function query() use ($query) {
    // do something with global variable $query
    return $query;
};

you can use $GLOBALS['query'] to access the global value of query variable.您可以使用 $GLOBALS['query'] 访问查询变量的全局值。 say you have a function where you want to use the query variable说你有一个 function 你想在其中使用查询变量

$query = "Some string"; 
function use_query_here() {     
    global $query;     
    $results = $query;     //Use $results here now or you can use $query also directly but if will risk mutating its value <br /> 
}

OR或者

function use_query_here() {
    $result = $GLOBALS['query'];     // Use $result variable here now 
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM