This question already has answers here:
Reference: What is variable scope, which variables are accessible from where and what are “undefined variable” errors?
(3个答案)
3年前关闭。
我的配置文件包含连接到服务器上数据库的函数,这是代码
配置文件
其他页面做一些事情
我明白了,并说了错误
注意:未定义的变量:/home/moudlepath/page.php中的dbh
那就是因为
和用法:
(3个答案)
3年前关闭。
我的配置文件包含连接到服务器上数据库的函数,这是代码
配置文件
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
define('USER', 'root');
define('PASS', '');
function communicate($dbname){
try {
$dbh = new PDO('mysql:host=serverip;dbname='.$dbname.'', USER, PASS);
$dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e) {
echo $e->getMessage();
$errorCode = $e->getCode();
}
}
?>
其他页面做一些事情
require('dbs/connfile.php');
if (isset($_GET['id'])) {
$accountname = 'dbname';
communicate($accountname);
$query = "SELECT * FROM datatbl";
$result= $dbh->prepare($query);
$result->execute();
while ($row = $result->fetch()) {
$cmail = $row['email'];
}
}
我明白了,并说了错误
注意:未定义的变量:/home/moudlepath/page.php中的dbh
那就是因为
$dbh
不是全局的,我如何在包含在其中的任何页面中使用该连接文件? 最佳答案
简单的解决方案是:
function communicate($dbname){
try {
$dbh = new PDO('mysql:host=serverip;dbname='.$dbname.'', USER, PASS);
$dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e) {
echo $e->getMessage();
$errorCode = $e->getCode();
}
return $dbh; // see this? return your $dbh
}
和用法:
$dbh = communicate($accountname);
关于php - php和Pdo包含与其他页面的连接,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/39711545/