我需要帮助编写PHP函数。我的代码:
function get_config() {
$db = dbServer::getInstance();
$mysqli = $db->getConnection();
$sql_query = 'SELECT * FROM server_config';
$result = $mysqli->query($sql_query);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$serverStatus = $row['server_status'];
$serverTitle = $row['server_title'];
}
}
}
现在,如果我想要调用该函数并且只有echo,请说$ serverTitle,我应该怎么做?即:
get_config($serverStatus)?
我是PHP的新手。
答案 0 :(得分:0)
只需使用" Echo"你想要什么回报。如果您只想要一件事,那么您将不得不根据行数来更改查询的方式,并可能为查询添加限制。
with t as (
select date,
convert(time, [start time]) as starttime,
dateadd(minute, duration * 5, convert(time, [start time])) as endtime
from roster
where date = '2016-08-08' and [staff] = 'ME'
)
select date, endtime, next_endtime
from (select t.*,
lead(endtime) over (partition by staff order by starttime) as next_endtime
from t
) t
where next_endtime is not null
order by starttime asc;
答案 1 :(得分:0)
编辑您的函数,使其接受将填充配置值的参数。例如,如果将函数声明更改为:
function get_config(&$serverStatus, &$serverTitle){...}
注意参数旁边的&
运算符。这意味着无论您对函数执行的任何操作都将在函数完成后继续存在。所以当你在函数内部时......
$serverStatus = $row['server_status'];
$serverTitle = $row['server_title'];
完成此功能后,这些值将可用。你可以使用这样的值:
//call the function, passing in the variables you want filled
get_config($status, $title);
//now, $status and $title have been filled with the DB values
echo $status;
<强>附录强>
您在评论中提到您喜欢WordPress调用get_param('paramName')
来获取特定参数的方法。以下可能有效:
//you pass an item name (must match a DB column) and function will return
// the item's value
function get_config($item) {
//static means the next time you call this function,
//the old value will be remembered.
static $row = null;
//if we fetched the row previously, just get the
//desired config item. This is a lot more efficient than
//making a DB query every time the function is called
if($row) return $row[$item];
$db = dbServer::getInstance();
$mysqli = $db->getConnection();
$sql_query = 'SELECT * FROM server_config';
$result = $mysqli->query($sql_query);
//save config data in $row so it will be remembered
// (because we declared this var as static)
$row = $result->fetch_assoc();
return $row[$item];//return the item requested
}
要使用此功能,只需将其传递给您需要的配置项的名称:
$status = get_config('server_status');
或者,如果您只想回应配置
echo get_config('server_title');