【问题标题】:Ensuring MySQL connection works in PHP function确保 MySQL 连接在 PHP 函数中有效
【发布时间】:2010-09-28 11:46:24
【问题描述】:

我有以下形式的代码:

<?php
function doSomething{
  //Do stuff with MySQL
  $con->tralalala();
}
$con = connectToDatabase;//This would actually be a line or two.
doSomething();
?>

这种(类型的)代码不起作用,因为 doSomething() 没有与数据库的连接。谁能解释为什么不?我在调用 doSomething()之前创建了 $con 连接。那么为什么函数的行为就像没有连接一样呢?

除了将连接传递给 doSomething($con) 之类的函数之外,有什么方法可以解决这个问题?

【问题讨论】:

    标签: php mysql scope mysqli


    【解决方案1】:

    您可能需要告诉它查看全局范围:

    
         function doSomething()
         {
             global $con;
             $con->tralalala();
         }
    

    【讨论】:

      猜你喜欢
      • 2013-12-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-04
      • 2011-01-18
      相关资源
      最近更新 更多