更新时间:2021-12-21 15:50:03
正如评论中指出的那样,这是一个范围界定问题.您的$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