【问题标题】:how to have defined connection within function for pdo communication with DB如何在函数内定义连接以与 DB 进行 pdo 通信
【发布时间】:2010-05-16 16:28:46
【问题描述】:

大家好,我刚开始尝试将我的查询结构转换为 PDO,但遇到了一个奇怪的问题。当我在函数内调用 pdo 查询连接并且连接包含在函数外部时,连接变为未定义。有人知道我在这里做错了什么吗?我只是在玩它,我的例子如下。

include("includes/connection.php");

function query(){
    $user='user';
$id='100';
$sql = 'SELECT * FROM users';
$stmt = $conn->prepare($sql);
$result=$stmt->execute(array($user, $id));

// now iterate over the result as if we obtained
// the $stmt in a call to PDO::query()
while($r = $stmt->fetch(PDO::FETCH_ASSOC))
{
echo "$r[username] $r[id] \n";
}
}
query();

【问题讨论】:

    标签: php mysql pdo


    【解决方案1】:

    您的function scope doesn't have access to the $conn variable, one way to work around this issues is by using globals。这是一个例子:

    function query(){
        global $conn;
        // your code here...
    }
    

    在 StackOverflow 中搜索 SingletonFactoryRegistryDependency Injection 模式以获得其他更高级和更优雅的替代方案.

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-04-14
      • 1970-01-01
      • 1970-01-01
      • 2015-08-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-19
      相关资源
      最近更新 更多