您好我只想编写自己的函数来从mysql获取选项值。我的index.php文件以这种方式显示:
<?
include ('config.php'); // here i have database connection details
include ('global-functions.php');
include ('minifier.php');
include ('cache-start.php');
?>
<!DOCTYPE html>
<html lang="jezyk strony z bazy danych">
USTAWIC META! sekcje head<br>
Sprawdzić czy dodac przekierowanie w php z www na bez www !!
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
(...) rest of the file
config.php文件看起来:
<?php
$host = "localhost";
$dbname = "xxxx";
$username = "xxx";
$password = "xxxx";
// Create connection
$conn = new mysqli($host, $username, $password, $dbname);
?>
现在我尝试执行指定选项的功能,我把这个函数放在global-functions.php中:
<?php
// Get option
function get_option( $option_name ) {
$sql = "SELECT opcja_value FROM opcje WHERE opcja_name='" . $option_name . "'";
$result = mysqli_fetch_array($conn->query($sql));
return $result[$option_name];
}
?>
现在我要调用函数来获取我的选项值。所以:
echo get_option('cache');
或做简单的if:
if ( get_option('cache') == '1' ) {
// do stuff
} else {
echo 'option disabled, sorry :(';
}
调用函数后,我得到致命错误:
致命错误:在null中调用成员函数query() 第10行的/framework/includes/global-functions.php
答案 0 :(得分:5)
范围范围! $conn
在您的函数范围内不存在。您可以使用global
声明它,或者将其传递给它,如下所示:
function get_option( $option_name, $conn ) { // Pass in $conn here
$sql = "SELECT opcja_value FROM opcje WHERE opcja_name='" . $option_name . "'";
$result = mysqli_fetch_array($conn->query($sql));
return $result[$option_name];
}
答案 1 :(得分:0)
我建议阅读this
您正在访问函数内的全局变量($conn
)。要在函数内部访问该变量,只需在函数开头使用global $conn;
。