2016-04-09 1 views
1

この関数は、データベースから行を返し、ブラウザに出力します。関数からPDOを呼び出します。

<?php 

$an_int = 12;  

// If this is an integer 

if (is_int($an_int)) 

{ 

$conn = new PDO('mysql:host=localhost;dbname=pushchat', 'pushchat', 'd]682\#%yI1nb3'); 
    global $conn; 

$stmt = $conn->prepare("SELECT IdPhoto, device_token, IdUser FROM photos ORDER BY IdPhoto DESC LIMIT 300 "); 

$stmt->execute(); 

$result = $stmt->fetch(PDO::FETCH_ASSOC); 

print_r($result); 

} 

?> 

上記のコードを標準機能からどのように呼び出すことができますか?現在、ブラウザはまだ何も出力していません。

<?php 

function new_function() 

{ 

$an_int = 12;  

// If this is an integer 

if (is_int($an_int)) 

{ 

$conn = new PDO('mysql:host=localhost;dbname=pushchat', 'pushchat', 'd]682\#%yI1nb3'); 
    global $conn; 

$stmt = $conn->prepare("SELECT IdPhoto, device_token, IdUser FROM photos ORDER BY IdPhoto DESC LIMIT 300 "); 

$stmt->execute(); 

$result = $stmt->fetch(PDO::FETCH_ASSOC); 

print_r($result); 
} 

} 
new_function(); 

?> 

この現在の構文では、ブラウザに出力が表示されません。 new_function機能の中からオリジナルのコードを呼び出す方法はありますか?

答えて

2

変数が宣言されています。global $conn; $ connはグローバルスコープにあるため、問題なく動作する理由は正確にはわかりません。

しかし、あなたは関数内であなたの global変数を宣言する2番目の場合には、機能ではなく、明らかに接続ハンドルを持つローカル変数 $connのグローバルスコープである $connを探します。

あなたの関数からglobal $connを削除するとうまくいくはずです。

可変スコープの詳細 - http://php.net/manual/en/language.variables.scope.php

関連する問題