Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error with custom PHP function: no variable being returned

Tags:

php

mysqli

Alright, so here is a look at my PHP function. I can confirm I AM connected to the database, as I can make updates to it with mysqli_query functions directly in the file.

<?php
function username_from_id($id) {
$id = mysqli_real_escape_string($id);
$query = mysqli_query($d,"SELECT `username` FROM `users` WHERE `id` = '$id'");
$result = mysqli_fetch_array($query);
$res = $result['username'];
return $res;
}
?>

The purpose of the function is to select the username of a user if their ID equals what is put into the query, then return it. In the file, it looks like this

<?php
include 'file_where_function_is.php';
$id = '1';
echo username_from_id($id);
?>

Nothing shows up. Any ideas?

like image 863
TheAnswers Avatar asked Dec 05 '25 20:12

TheAnswers


1 Answers

As pointed out in comments, this is a scoping issue. Your $d variable (mysqli instance) is not in scope within username_from_id. Here's how to fix it...

function username_from_id(mysqli $d, $id) {
    if (!$stmt = $d->prepare('SELECT username FROM users WHERE id = ? LIMIT 1')) {
        throw new Exception($d->error, $d->errno);
    }
    $stmt->bind_param('i', $id);

    if (!$stmt->execute()) {
        throw new Exception($stmt->error, $stmt->errno);
    }

    $stmt->bind_result($username);

    if ($stmt->fetch()) {
        return $username;
    }
    return null;
}

and call it like this

include 'file_where_function_is.php';
$id = 1;
echo username_from_id($d, $id); // assuming $d exists in this scope
like image 146
Phil Avatar answered Dec 08 '25 12:12

Phil



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!