我最近开始学习php中的函数式编程,我不知道为什么这行不通。 我有一个单独的文件“ functions.php”,我正试图从索引文件中调用一个函数。
functions.php:
function connectSql() {
$servername = "";
$username = "";
$password = "";
$dbname = "";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Yhteys katkesi: " . $conn->
}
}
function displayPublic() {
connectSql();
$sql = "SELECT * FROM projects WHERE public == true ORDER BY dateStarted DESC";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()){
echo "Project found";
}
} else {
echo "Ei tuloksia";
}
$conn->close();
}
index.php:
include 'functions.php';
displayPublic();
答案 0 :(得分:2)
您没有返回$conn
尝试
function connectSql() {
$servername = "";
$username = "";
$password = "";
$dbname = "";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Yhteys katkesi: " . $conn->connect_error);
} else {
return $conn;
}
}
function displayPublic() {
$conn = connectSql();
$sql = "SELECT * FROM projects WHERE public == true ORDER BY dateStarted DESC";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()){
echo "Project found";
}
} else {
echo "Ei tuloksia";
}
$conn->close();
}
或将$conn
设置为全局变量
<?php
$conn;
function connectSql() {
$servername = "";
$username = "";
$password = "";
$dbname = "";
global $conn;
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Yhteys katkesi: " . $conn->connect_error);
}
}
function displayPublic() {
connectSql();
global $conn;
$sql = "SELECT * FROM projects WHERE public == true ORDER BY dateStarted DESC";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()){
echo "Project found";
}
} else {
echo "Ei tuloksia";
}
$conn->close();
}