Reebal
Reebal

Reputation: 59

Issue with PDO Connection

i am new to this so dont be rude :D

I have 3 file: database.php, init.php and user.php

Here the 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();

Here the 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());
}

And here the 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;
}

So the error message:

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 

The function userExists() is called in another file named login.php. In login.php i have already required init.php. The error message appears when i want to login.

So i hope you can help me.

Thx

Upvotes: 2

Views: 53

Answers (2)

Phoenix404
Phoenix404

Reputation: 1058

In your userExists function you are calling $conn variable which isn't global scope (Give a small look here)..

You can use one of these:

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 use of $GLOBALS variable

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

Upvotes: 1

joconja
joconja

Reputation: 361

$conn is not available in your function since it is in a different scope. Pass it as a parameter or declare it as a global variable.

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

or

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

Upvotes: 3

Related Questions