2017-03-13 24 views
0

私は自分のデータベースのユーザー名を出力するページを作成しようとしています。その間に、私はという2つのエラーがあります。 "未定義の変数:conn.function.php""function.phpのヌルでメンバ関数prepare()を呼び出す"未定義変数と関数prepare()on null

のfunctions.phpからライン6は

<?php 

require 'database.php'; 

function getUser($id, $field) { 
    $query = $conn->prepare("SELECT $field FROM users WHERE id='$id'"); //error line 
    $query->bind_param($id, $field); 
    $query->execute(); 
    $run = $query->fetch(PDO::FETCH_ASSOC); 

    return $run[$field]; 
} 

?> 

database.phpで

<?php 

// 3 variables below removed 
$dsn = ''; 
$username = ''; 
$password = ''; 

try { 
    $conn = new PDO($dsn, $username, $password); 
} catch(PDOException $e) { 
    die("Connection denied: " . $e->getMessage()); 
} 

?> 

members.php

<?php 

    require 'functions.php'; 
    require 'database.php'; 

    $stmt = $conn->prepare('SELECT id FROM users'); 
    $stmt->execute(); 

    while($run_mem = $stmt->fetch(PDO::FETCH_ASSOC)) { 
     $user_id = $run_mem['id']; 
     $usernames = getUser($user_id, 'username'); 
     echo $usernames; 

    } 

?> 
エラーであります

同じ変数を使用していても、prepare()ステートメントのmembers.phpにエラーが表示されません。$ conn

解決策が見つかったら大いに感謝します!

+3

[変数のスコープ](http://www.php.net/manual/en/language.variables.scope.php) –

+0

'$ conn'はどのように関数に入りますか? – AbraCadaver

+0

ありがとうございます@AbraCadaver私はちょうどカットアンドペースト 'database.php'が必要です。その関数の内部に –

答えて

0

あなたはこの次のように関数の宣言ステップで関数のパラメータとして$conn変数を渡すことができます解決するために、変数のスコープの問題、

を持っている:あなたがに行くときに

function getUser($conn, $id, $field) { 

を次のように接続変数を渡す、あなたの関数を呼び出す:

$usernames = getUser($conn, $user_id, 'username');