我有关于将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>
?>
答案 0 :(得分:7)
答案 1 :(得分:7)
答案 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
。