0

Why does not my connection to my database work even after I've connected?

This is the file I store my connection in: dbase.php

<?php
function connect()
{
    try
    {   
        $conn = new PDO('mysql:host='.DB_HOST.';dbname='.DB_NAME.'',DB_USER,DB_PASSWORD);
        $conn ->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_SILENT);

    }catch(PDOException $e) 
    {
        echo 'Error in reaching database: '.$e->getMessage();
        #Send an email to the admin
        #Display the error page
        die();
    }
        return $conn;
}
?>

Then comes this page: index.php : where I include the above file.

<?php
include_once ($_SERVER['DOCUMENT_ROOT'].'\attach\dbase.php');

$conn = connect();

$what = 1;

$stmt = $conn->prepare("select id as id, name as name, description as description, level as level from products where level = :what and country = 'US'");
$stmt->bindParam(':what', $what);
$stmt->execute();

$rows = $stmt->rowCount();

while($row = $stmt->fetch())
{  
    echo $row['name']." ".$row['id'];
    echo "<br><br>";

    fetchElements($row['level'],$row['id']);
}

function fetchElements($one,$two)
{   
    //This is line 25
    $elements = $conn->prepare("select id as id, level as level, name as name, description as description from products where level > :what and parent = :parent and country = 'US'");
    $elements->bindParam(':what', $one);
    $elements->bindParam(':parent', $two);
    $elements->execute();
        //Sql for 3 need to be different
    while($row = $elements->fetch())
    {  
        echo $row['name']." Id: ".$row['id']." Level: ".$row['level']."<br>";
        if($one != 3)
        {
            fetchElements($row['level'],$row['id']);
        }
    }
    echo "<br>";
}
?>

Even when I've connected to the dbase in this page above, when the script calls the function, I get: Notice: Undefined variable: conn in C:\web\apache\htdocs\index.php on line 25 Fatal error: Call to a member function prepare() on a non-object in C:\web\apache\htdocs\index.php on line 25. I've marked line 25 in the file.

Why is this happending, and how do I solve this?`

Norman
  • 5,685
  • 19
  • 74
  • 128

3 Answers3

1

Change

function fetchElements($one,$two)
{ 
   ...

to

function fetchElements($one,$two)
{ 
   global $conn;
   ...
peterm
  • 85,273
  • 13
  • 129
  • 142
  • Thing is, wont doing this start a new connection again? I've already connected at the beginning of the script... – Norman May 08 '13 at 04:25
  • @Norman It won't. It just makes the variable (`$conn`) accessible in your function. Without `global` it's out of the scope. – peterm May 08 '13 at 04:34
1

pass here $conn as parameter in fetchElements function

function fetchElements($one,$two, $conn) {

and assign it here

fetchElements($row['level'],$row['id'], $conn);

Don't use GLOBAL

Community
  • 1
  • 1
Yogesh Suthar
  • 29,554
  • 17
  • 66
  • 96
1

Global variables (like $conn) are not automatically available in functions.

You got two ways:

A: Pass the variable as function parameter:

function fetchElements($conn,$one,$two)
{
....
}

Call with fetchElements($conn,$one,$two);

B: Use the global keyword:

function fetchElements($one,$two)
{
    global $conn;
    ....
}

Method A is more flexible and better (in my opinion), because you could for example have multiple PDO connections and can decide which one the function should use on a per-call basis.

Lukas
  • 1,409
  • 8
  • 20
  • Thing is, wont doing this start a new connection again? I've already connected at the beginning of the script... – Norman May 08 '13 at 04:31
  • No, `$conn` is only a reference to the PDO object. As a matter of fact, using `global` will always glue the variables inside and outside a function together (that is, changing it in the function while change it outside, too). However, objects are always referenced - not copied - unless you specifically use the `clone` keyword. – Lukas May 08 '13 at 04:48