0

为什么即使在我连接后,我与我的数据库的连接也无法正常工作?

这是我存储连接的文件: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;
}
?>

然后是这个页面::index.php我在其中包含上述文件。

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

即使我已经连接到上面这个页面中的 dbase,当脚本调用该函数时,我得到: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.

为什么会发生这种情况,我该如何解决?

4

3 回答 3

1

改变

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

function fetchElements($one,$two)
{ 
   global $conn;
   ...
于 2013-05-08T04:15:25.010 回答
1

在函数$conn中作为参数传递这里fetchElements

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

并在此处分配

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

不要使用全球

于 2013-05-08T04:16:17.897 回答
1

全局变量(如$conn)不会自动在函数中可用。

你有两种方法:

A:将变量作为函数参数传递:

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

打电话给fetchElements($conn,$one,$two);

B:使用global关键字:

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

方法A更加灵活和更好(在我看来),因为您可以拥有多个 PDO 连接,并且可以决定该函数应该在每次调用的基础上使用哪一个。

于 2013-05-08T04:16:25.880 回答