假设我有一个名为 mytable 的表,其中包含以下列:
------------------------
| id | field1 | field2 |
------------------------
假设我有一个 html 文件:
<body>
<?php
include ('connect-db.php');
include ('function.php');
?>
<ul>
<?php
myfunction();
while($row = $result->fetch_assoc()){
echo "<li>".$row['field1']." and ". $row[field2]."</li>";
}
?>
</ul>
</body>
这是我的 connect-db.php
文件:
<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "dbname";
$conn=new mysqli($servername, $username, $password, $dbname);
?>
这是我的function.php
文件:
<?php
function myfunction(){
$sql = "SELECT * FROM mytable";
$result = $conn->query($sql);
}
?>
如何回显field1和field 2?因为我有错误
最佳答案
Any variable used inside a function is by default limited to the local function scope.
您可以在这里阅读更多相关信息:Variable scope .如何解决?将 $conn
作为 myfunction
的参数传递,并返回 $result
。
function myfunction(mysqli $conn) {
$sql = "SELECT * FROM mytable";
return $conn->query($sql);
}
然后你可以调用它
$result = myfunction($conn);
关于php - 返回查询结果的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41085251/