This question already has an answer here:
这个问题在这里已有答案:
- Reference: What is variable scope, which variables are accessible from where and what are “undefined variable” errors? 3 answers
参考:什么是变量范围,哪些变量可以从哪里访问,什么是“未定义变量”错误? 3个答案
Here is my code:
这是我的代码:
<?php
$db_host = 'localhost';
$db_user = 'root';
$db_pass = 'root';
$db_database = 'drmahima_com';
$link = mysqli_connect($db_host,$db_user,$db_pass,$db_database) or die('Unable to establish a DB connection');
mysqli_query($link, "SET names UTF8");
function temp() {
$patient = mysqli_fetch_assoc(mysqli_query($link, "SELECT name,dob FROM patients WHERE id='69'"));
echo $patient['name'];
}
temp();
?>
When I run this, the query doesn't seem to execute and nothing shows up on the page. However, if I remove the function and just change the code to this:
当我运行它时,查询似乎没有执行,并且页面上没有显示任何内容。但是,如果我删除该函数,只需将代码更改为:
<?php
$db_host = 'localhost';
$db_user = 'root';
$db_pass = 'root';
$db_database = 'drmahima_com';
$link = mysqli_connect($db_host,$db_user,$db_pass,$db_database) or die('Unable to establish a DB connection');
mysqli_query($link, "SET names UTF8");
// function temp() {
$patient = mysqli_fetch_assoc(mysqli_query($link, "SELECT name,dob FROM patients WHERE id='69'"));
echo $patient['name'];
// }
// temp();
?>
It works, and the patient's name is displayed.
它有效,并显示患者的姓名。
What is going on here?
这里发生了什么?
2 个解决方案
#1
Pass the $link to function as a parameter. Try this:
将$ link作为参数传递给函数。试试这个:
<?php
$db_host = 'localhost';
$db_user = 'root';
$db_pass = 'root';
$db_database = 'drmahima_com';
$link = mysqli_connect($db_host,$db_user,$db_pass,$db_database) or die('Unable to establish a DB connection');
mysqli_query($link, "SET names UTF8");
function temp($link) {
$patient = mysqli_fetch_assoc(mysqli_query($link, "SELECT name,dob FROM patients WHERE id='69'"));
echo $patient['name'];
}
temp($link);
?>
#2
Pass $link
to the function. It is not working because of the scope
of that variable. Try with -
将$ link传递给该函数。由于该变量的范围,它无法正常工作。尝试 -
function temp($link) {
$patient = mysqli_fetch_assoc(mysqli_query($link, "SELECT name,dob FROM patients WHERE id='69'"));
echo $patient['name'];
}
temp($link);
#1
Pass the $link to function as a parameter. Try this:
将$ link作为参数传递给函数。试试这个:
<?php
$db_host = 'localhost';
$db_user = 'root';
$db_pass = 'root';
$db_database = 'drmahima_com';
$link = mysqli_connect($db_host,$db_user,$db_pass,$db_database) or die('Unable to establish a DB connection');
mysqli_query($link, "SET names UTF8");
function temp($link) {
$patient = mysqli_fetch_assoc(mysqli_query($link, "SELECT name,dob FROM patients WHERE id='69'"));
echo $patient['name'];
}
temp($link);
?>
#2
Pass $link
to the function. It is not working because of the scope
of that variable. Try with -
将$ link传递给该函数。由于该变量的范围,它无法正常工作。尝试 -
function temp($link) {
$patient = mysqli_fetch_assoc(mysqli_query($link, "SELECT name,dob FROM patients WHERE id='69'"));
echo $patient['name'];
}
temp($link);