自定义PHP函数出错:未返回任何变量 [英] Error with custom PHP function: no variable being returned
问题描述
好的,下面是我的PHP函数.我可以确认我已连接到数据库,因为可以直接在文件中使用mysqli_query函数对其进行更新.
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;
}
?>
该函数的目的是,如果用户的ID等于查询中输入的用户名,则选择该用户名,然后将其返回.在文件中,看起来像这样
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?
推荐答案
正如评论中指出的那样,这是一个范围界定问题.您的$d
变量(mysqli
实例)不在username_from_id
的范围内.这是解决方法...
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;
}
并这样称呼它
include 'file_where_function_is.php';
$id = 1;
echo username_from_id($d, $id); // assuming $d exists in this scope
这篇关于自定义PHP函数出错:未返回任何变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!