newbieDevs newbieDevs - 1 month ago 5x
PHP Question

PHP function, call only one variable

I need help with a PHP function im writing. My code:

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'];

Now, If I'd want to call the function and only echo let's say, $serverTitle, how should I do that? I.e:


I'm a total rookie when it comes to PHP.


Edit your function so that it accepts arguments that will be filled with the config values. For instance, if you change the function declaration to:

function get_config(&$serverStatus, &$serverTitle){...}

Notice the & operator next to the parameters. It means that whatever you do to the variables you pass into the functions will survive after the function is finished. So when inside the function you do...

 $serverStatus = $row['server_status']; 
 $serverTitle = $row['server_title'];

These values will be available after the function is done. You would use the values like this:

//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;


you mentioned in the comments that you like the WordPress approach of calling get_param('paramName') to fetch a specific detail. This can be done as well. Something like the following might work:

//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

To use this the function, just pass it the name of the config item you need:

$status = get_config('server_status');

Or if you just want to echo the configuration

echo get_config('server_title');