我有一个带有index.php页面的登录项目,该页面从另一个脚本文件core.inc.php调用loggin函数,具体取决于index.php页面中所需的连接脚本connect.inc.php core.inc.php看不到连接对象抛出一个未定义的变量错误.....为什么? 试图通过print_r()测试$ conn对象并且没有工作并抛出未定义的var错误.... 请帮忙 这是index.php代码:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Home page</title>
</head>
<?php
require("connect.inc.php");
require("core.inc.php");
if(loggedin()){
echo 'Welcome ' . getuserfield('fname').' ' .
getuserfield('surname') .' <a href="logout.php">Logout!</a>';
}
else {include("loginform.inc.php"); echo "<a href='register.php'> Register! </a>";}
?>
<body>
</body>
</html>
这是connect.inc.php文件:
<?php
define("MYSQL_HOST", "mysql:host=localhost;dbname=a_database;charset=utf8");
define("MYSQL_USER", "root");
define("MYSQL_PASS", "123456");
try{
$conn = new PDO(MYSQL_HOST,MYSQL_USER,MYSQL_PASS);
$conn->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_WARNING);
$conn->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
$conn->setAttribute(PDO::ATTR_CASE,PDO::CASE_LOWER);
}
catch(PDOException $e){
echo $e-> getMessage();
}
?>
<?php
// to create a login session
ob_start();
session_start();
// define variable to the login form
$current_file =$_SERVER['SCRIPT_NAME'];
//define the referer where the command comes from
if(isset($_SERVER['HTTP_REFERER']) && !empty($_SERVER['HTTP_REFERER'])){
$http_referer= $_SERVER['HTTP_REFERER'];
}
//check if logged in or not
function loggedin(){
if(isset($_SESSION['user_id']) && !empty($_SESSION['user_id'])){
return true;
}
else{return false;}
}
////////////////
function getuserfield($field){
$sql = "SELECT `$field` FROM `users_tb` WHERE `id`='" .$_SESSION['user_id']. "'";
echo "connection : " ; print_r($conn);
if(@$run = $conn->query($sql)){
echo "table connected";
if ($sql_result = $run->fetch(PDO::FETCH_ASSOC)){
echo $run_result[$field];
//return $sql_result[$field];
}
else {return "Unknown";}
}
}
?>
问题是在core.inc.file中看不到连接$ conn对象抛出getuserfield($ field)函数回调 那有什么不对? 请帮助:)
答案 0 :(得分:1)
$conn
对象在getuserfield
函数中不可见,因为在函数内部,您无法访问默认情况下在外部定义的变量。您需要使用global
关键字来访问变量:
function getuserfield($field){
global $conn;
/* ... */
}
虽然这可以解决您的问题,但我建议不要使用global
,您的代码会变得混乱且难以调试。更简洁的方法是创建一个处理数据库操作的类,在这个类中,您可以将连接存储在静态变量中:
class MyDB {
public static $conn;
public static function connect() {
try{
self::$conn = new PDO(MYSQL_HOST,MYSQL_USER,MYSQL_PASS);
self::$conn->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_WARNING);
self::$conn->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
self::$conn->setAttribute(PDO::ATTR_CASE,PDO::CASE_LOWER);
}
catch(PDOException $e){
echo $e->getMessage();
}
}
}
MyDB::connect();
这样,您可以在任何地方访问连接对象,而无需将global
与MyDB::$conn