assume that i have a table named mytable with columns:
------------------------
| id | field1 | field2 |
------------------------
and assume i have a html files:
<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>
this is my connect-db.php
file:
<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "dbname";
$conn=new mysqli($servername, $username, $password, $dbname);
?>
and this is my function.php
file:
<?php
function myfunction(){
$sql = "SELECT * FROM mytable";
$result = $conn->query($sql);
}
?>
How to echo the field1 and field 2? because i have and error
Any variable used inside a function is by default limited to the local function scope.
You can read more about it here: Variable scope . How to fix it? Pass the $conn
as an argument of myfunction
, and return the $result
.
function myfunction(mysqli $conn) {
$sql = "SELECT * FROM mytable";
return $conn->query($sql);
}
then you can call it with
$result = myfunction($conn);
Make sure the following changes.....
at main page
<body>
<?php
include ('connect-db.php');
include ('function.php');
?>
<ul>
<?php
$result= myfunction();
while($row = $result->fetch_assoc()){
echo "<li>".$row['field1']." and ". $row[field2]."</li>";
}
?>
</ul>
</body>
At your function file..
<?php
include ('connect-db.php');
function myfunction(){
$sql = "SELECT * FROM mytable";
$result = $conn->query($sql);
return $result;
}
?>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.