3

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?

6
  • 3
    $d is never defined in username_from_id Commented May 16, 2014 at 4:30
  • Add error reporting to the top of your file(s) error_reporting(E_ALL); ini_set('display_errors', 1); mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT); if you're not already doing so. Commented May 16, 2014 at 4:31
  • 2
    $d should still be brought into the scope of the function if referenced. It must be passed into the function or retrieved from the global scope at the beginning of the function by using the global keyword. Commented May 16, 2014 at 4:33
  • 1
    There are 2 things that can be done: 1) pass $d as a function argument 2) omit $d and the mysqli_query() will use last used connection (which I find a great example of OOP fail in PHP) UPDATE: actually it has to be checked, as documentation describe that behavior for mysql_query() but there's nothing like that about mysqli_query(). Commented May 16, 2014 at 4:33
  • He "can make updates to it with mysqli_query functions directly in the file" which probably means he's testing that right after connecting to the database, where $d is initialized. His function has never heard of $d Commented May 16, 2014 at 4:40

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.