PDO连接问题

时间:2017-01-03 09:34:00

标签: php mysql pdo

我是新手,所以不要粗鲁:D

我有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 

在另一个名为login.php的文件中调用函数userExists()。在login.php中,我已经需要init.php。我想登录时会出现错误消息。

所以我希望你能帮助我。

THX

2 个答案:

答案 0 :(得分:3)

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

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

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

答案 1 :(得分: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;
}

OR

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;
}