wakey
wakey

Reputation: 2399

Database select function in PHP?

I am trying to create a function in PHP that accepts two arguments, one being the SQL for a mysqli query and the other being the name I would like to be set as the variable name for the resulting array. Here it is so far:

<?php

function dbSelect($sql,$name) {
    include "connect.php";
    if($results = $db->query($sql)) {
        if($results->num_rows) {
            while($row = $results->fetch_object()) {
                ${$name}[] = $row;
            }
            $results->free();
        }
    }
    return ${$name};
}

Within the referenced connect.php file is this code

$db = new mysqli('127.0.0.1', 'admin', 'PASSWORD', 'DB_NAME');

However it does not seem to work in its current state. I do not get any errors when calling the function "dbSelect($sql, 'test');" however when I try to reference the supposedly created variable (in this case, $test) I get an undefined error.

Any suggestions or tips on how to fix this?

Thanks in advance.

Upvotes: 1

Views: 132

Answers (2)

Bill Karwin
Bill Karwin

Reputation: 562230

The ${$name} variable you're assigning to has local scope. That is, the variable disappears as this function returns. Using a variable-variable doesn't make that variable global.

I would recommend you just name the array anything inside your function, and then return the array. Then you can assign its return value to your desired variable instead of passing the variable name.

$test = dbSelect($sql);

You could try to declare global ${$name} inside the function to write to a variable of global scope, but IMHO it's not worth it. It's a better habit to avoid writing functions that have weird side effects on global variables. Keep it simple, just return the results.

Upvotes: 2

AbraCadaver
AbraCadaver

Reputation: 78994

The variable variable ${$name} has no practical use in this function. The function returns an array with no variable name. You name it when you assign the function return:

$whatEverYouWant = dbSelect('some sql');

function dbSelect($sql) {
    include "connect.php";
    if($results = $db->query($sql)) {
        if($results->num_rows) {
            while($row = $results->fetch_object()) {
                $array[] = $row;
            }
            $results->free();
            return $array;
        }
    }
    return false;    
}

Return false or maybe an empty array() if there are no results or an error.

Upvotes: 2

Related Questions