Matt Kent
Matt Kent

Reputation: 1185

Return isn't working in my PHP function

I have created this select function with no escape to run simple queries where the data isn't coming from a user.

My function works and I can do what I intended with global $var however when I tried to return the value rather than make it a global variable it didn't work. I am just curious as to why this is.

Here is my function:

    function SelectQuery_NO_ESCAPE($row, $table, $row, $value) {
    $Database = DatabaseConnection();
    $sql_query = "SELECT $row FROM $table WHERE $row = '$value'";
    $select_result = $Database['Connection']->query($sql_query) or die(mysqli_error($Database['Connection']));
    if ($select_row = $select_result->fetch_assoc()) {
        global $select_row;
        $select_row = $select_row[$row];

    }
}

I have a test.php file where I use the function:

SelectQuery_NO_ESCAPE('ip', 'ip_address', 'ip', '1');
echo $select_row;

This works and outputs 1. If I try to take out the global and just return the variable $row_value it doesn't work.

Why is this?

Upvotes: 0

Views: 63

Answers (1)

AbraCadaver
AbraCadaver

Reputation: 79024

Return it:

if ($select_row = $select_result->fetch_assoc()) {
    return $select_row[$row];
}

Assign the returned value:

$something = SelectQuery_NO_ESCAPE('ip', 'ip_address', 'ip', '1');
echo $something;
//or
echo SelectQuery_NO_ESCAPE('ip', 'ip_address', 'ip', '1');

Upvotes: 4

Related Questions