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

上記のこのページでデータベースに接続した場合でも、スクリプトが関数を呼び出すと、次のようになります。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

グローバル変数 ( など$conn) は、関数で自動的に使用できるわけではありません。

次の 2 つの方法があります。

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 に答える
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 に答える