如何将mysql放入php函数中?

时间:2011-05-23 23:51:04

标签: php mysql

我有关于将mysql放入函数showMsg()的问题。如果它没有被函数showMsg()包装,mysql工作正常,但当我用函数showMsg()包装它时,它会给出错误消息“Warning:mysql_query():提供的参数不是有效的”。如何将mysql放入php函数中?以下是我的代码:

<?php    
function showMsg(){   
        $query2 = "SELECT id, message, username, datetime FROM messageslive ORDER BY id DESC LIMIT 20";
        $result2 = mysql_query($query2,$connection) or die (mysql_error());
        confirm_query($result2);
        $num = mysql_num_rows($result2); 
        while($msginfo = mysql_fetch_array($result2)){
            echo $msginfo['message'];
            echo $msginfo['username'];
        }
}

<div>
   <?php showMsg(); ?>
</div>
?>

6 个答案:

答案 0 :(得分:7)

您可能需要:

global $connection;

(在函数内部,即。)

请参阅Variable Scope

答案 1 :(得分:7)

  1. 切勿使用global$connection作为参数传递给您的函数。

  2. 逻辑和表示应该分开 阅读MVC:herehere

  3. 全局变量是邪恶的,永远不会使用它。如果有人建议 - 忽略他们的所有答案。

答案 2 :(得分:3)

正如大家所提到的,这个问题与变量范围有关。您可以考虑使用OOP方法,而不是添加global $connection;,并考虑:

答:将$ connection变量传递给函数。

B:将相关函数放在类中,并将DB连接传递给Class构造函数。 例如:

class YourClass  {

   private $connection;

   public function __construct($connection) {
       $this->connection = $connection;
   }

   public function showMsg(){   
        $query2 = "SELECT id, message, username, datetime FROM messageslive ORDER BY id DESC LIMIT 20";
        $result2 = mysql_query($query2,$this->connection) or die (mysql_error());
        confirm_query($result2);
        $num = mysql_num_rows($result2); 
        while($msginfo = mysql_fetch_array($result2)){
            echo $msginfo['message'];
            echo $msginfo['username'];
        }
   }

}

我没有足够的代表发表评论。但我也喜欢OZ_的回答:)

答案 3 :(得分:2)

$connection变量没有分配值。以下代码应解决您的问题(在函数的开头添加它):

global $connection;

但是你应该意识到这样一个事实,即使用全局变量并不是一个好主意,你可能想:

  • (最好)在函数参数中传递$connection变量,或
  • $connection声明从函数外部移到函数中(如果它不会导致其他问题),或者
  • 在函数中重新声明$connection变量(再次:如果它不会导致其他问题),

答案 4 :(得分:1)

因为变量是函数的局部变量。您需要在函数中添加它:

global $connection;

答案 5 :(得分:-1)

简单地说,由于variable scope,函数会忽略外部变量。您必须使用global将变量声明为来自外部,或者您可以通过参数发送$connection