2017-01-03 73 views
2

我是新来这个,所以不要粗鲁:d问题与PDO连接

我有3个文件:database.php中,和的init.php user.php的

这里的init.php:

<?php 
ini_set('display_errors', 1); 
ini_set('display_startup_errors', 1); 
error_reporting(E_ALL); 

session_start(); 

require 'database.php'; 
require 'functions/user.php'; 
$errors = array(); 

这里database.php中:

<?php 
$db_host = "localhost"; 
$db_name = "xxxx"; 
$db_user = "xxxx"; 
$db_pw = "xxxx"; 

try { 
    $conn = new PDO("mysql:host=$db_host;dbname=$db_name;", $db_user, $db_pw); 
} catch(PDOException $e) { 
    die("Verbindung fehlgeschlagen: " . $e->getMessage()); 
} 

而这里user.php的:

<?php 
function userExists($user) { 
    $sql = "SELECT * FROM user WHERE email = :email"; 
    $stmt = $conn->prepare($sql); 
    $stmt->bindParam(':email', $user); 
    $stmt->execute(); 
    $results = $stmt->fetch(PDO::FETCH_ASSOC); 
    if(count($results) > 0) return true; 
     return false; 
} 

所以错误消息:

Notice: Undefined variable: conn in /mnt/web109/b2/35/57848035/htdocs/includes/functions/user.php on line 4 Fatal error: Call to a member function prepare() on null in /mnt/web109/b2/35/57848035/htdocs/includes/functions/user.php on line 4 

功能userExists()被调用在另一个文件命名为login.php中。在login.php我已经需要init.php。当我想登录时出现错误消息。

所以我希望你能帮助我。

THX

+1

开始与理解变量的作用域。 –

+0

我认为这足以在ini.php中需要databse.php和user.php ..我几天前在视频中看到了它,它在那里起作用,所以我现在尝试它并获得错误。 – Reebal

回答

3

$conn是不是在你的函数可用,因为它是在不同的范围。将其作为参数传递或将其声明为全局变量。

function userExists($user, $conn){ 
    // ... 
} 

function userExists($user){ 
    global $conn; 
    // ... 
} 
+2

作为一个方面说明,使用“全局”通常被认为是不好的做法。 – ggg

+0

似乎工作。但我认为我的功能逻辑有一个问题.. – Reebal

+0

非常感谢你! – Reebal

1

在你userExists功能您呼叫$conn变量,它不是全局范围(Give a small look here)..

您可以使用下列操作之一:

function userExists($user, $conn){ 

    $sql = "SELECT * FROM user WHERE email = :email"; 
    $stmt = $conn->prepare($sql); 
    $stmt->bindParam(':email', $user); 
    $stmt->execute(); 
    $results = $stmt->fetch(PDO::FETCH_ASSOC); 
    if(count($results) > 0) return true; 
    return false; 
} 

function userExists($user){ 
    global $conn; //<--- bad practi 
    $sql = "SELECT * FROM user WHERE email = :email"; 
    $stmt = $conn->prepare($sql); 
    $stmt->bindParam(':email', $user); 
    $stmt->execute(); 
    $results = $stmt->fetch(PDO::FETCH_ASSOC); 
    if(count($results) > 0) return true; 
    return false; 
} 

OR 使用$GLOBALS变量

function userExists($user){ 
    $sql = "SELECT * FROM user WHERE email = :email"; 
    $stmt = $GLOBALS['conn']->prepare($sql); 
    $stmt->bindParam(':email', $user); 
    $stmt->execute(); 
    $results = $stmt->fetch(PDO::FETCH_ASSOC); 
    if(count($results) > 0) return true; 
    return false; 
} 
+0

非常感谢! – Reebal

+0

'$ GLOBALS [$ conn]'应该是'$ GLOBALS ['conn']' – joconja

+0

@Reebal your welcome! ! joconja感谢主席先生的纠正 –