使用表名作为函数参数

时间:2014-09-24 20:20:33

标签: php mysql wordpress

我正在创建一个函数,该函数的作用是检查指定表中是否有数据。

功能

function check_empty_table($tablename, $response) {

global $wpdb;

$result = $wpdb->get_results("SELECT * FROM $tablename");

 if(empty($result)){
  $response = '';
  return $response; 
  }

 if(!empty($result)){
 $response = $result;
 return $response; 
 }

}

这里我使用的函数包括'变量'作为表名..

check_empty_table('variables', $response);
$variables = $response;
echo '<select name="' . $id . '" id="' . $id . '" class="select">';
echo '<option value="">Variable Name</option>';
foreach ( $variables as $variable ){
echo '<option' . selected( esc_attr( $meta ), $variable->name, false ) . ' value="' . $variable->name . '">' . $variable->name . '</option>';
                         }
echo '</select><br />' . $desc;

我不确定哪个不起作用,在它结束时,即使表中有数据,$ response也会返回空。

谢谢..

1 个答案:

答案 0 :(得分:2)

您需要通过引用传递$ response(&$response),或者只需执行:

$variables = check_empty_table('variables', $response);

通过参考说明

通过引用传递响应参数(function check_empty_table($tablename, &$response) {...,注意&),函数调用中的第二个参数将获得其值,导致代码仍然有效。这可能令人困惑,因为函数内部和外部的变量具有相同的名称,因此这是一个非常简单的示例:

function f(&$ref) {
    return ++$ref;
}

$a = 1;
$a = f($a); // $a is now 2, of course
f($a);      // no assignment, but what's the value of $a now?