Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/236.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 从函数调用PDO_Php_Mysql_Pdo - Fatal编程技术网

Php 从函数调用PDO

Php 从函数调用PDO,php,mysql,pdo,Php,Mysql,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 Id

此函数用于从数据库返回一行,并在浏览器中打印该行

<?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\u函数中调用我的原始代码
函数。。。有什么想法吗?

嗯,在您的第一个文件中,您声明了一个
global
变量
global$conn我不知道为什么,但无论如何,这样做不会有任何问题,因为$conn在全局范围内

但在第二种情况下,当您在函数中声明
全局
变量时,函数将搜索全局范围内的
$conn
,而不是局部变量
$conn
,后者显然具有连接句柄

从函数中删除
global$conn
,它应该可以工作

有关变量作用域的详细信息-