让我们创建一个非常简单的示例文件:
index.php
:
<?php
$connection = mysqli_connect('localhost', 'user', 'pass', 'db');
// connection established successfully
echo 'doing something here for like 500 lines of code';
include('functions.php');
echo countCTR(12, 15);
?>
现在,问题出现在functions.php
:中
<?php
function countCTR($input1, $input2){
/* in this function I need my database connection ($connection)
which was established already in index.php before this
file was included. however, the $connection isn't open
inside this function. Do I have to execute mysqli_connect
inside every function I define?
*/
}
?>
这里对此进行了解释。
您有两种选择:将$connection设置为全局连接,或者将其传递给方法。我更喜欢后者——全局变量让我紧张。
要传入连接,请按如下方式更改函数定义:
<?php
function countCTR($input1, $input2, $connection){
/* in this function I need my database connection ($connection)
which was established already in index.php before this
file was included. however, the $connection isn't open
inside this function. Do I have to execute mysqli_connect
inside every function I define?
*/
}
?>
并在index.php中调用它,如下所示:
echo countCTR(12, 15, $connection);
正如评论中提到的,思考故障模式并以结构化的方式处理异常是一种很好的做法。您发布的示例代码(我已经对其进行了修改)在将连接传递到函数之前没有检查连接是否有效;它也不会检查该连接在函数中是否仍然可用。
你需要确保你的错误处理策略能解决这个问题,但这与你最初的问题并不严格相关。
你不应该这样做
只需使用global
关键字。
function countCTR($input1, $input2){
global $connection;
}
不,你不会。只创建一个连接就足够了。好主意是在另一个文件中创建一个数据库连接,然后将其包含在index.php或任何其他文件中。
示例:database.php
<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
?>
示例:index.php
<?php include("database.php");?>
希望这有帮助=)
可以使用两种方法1.将$connection链接标识符声明为全局
<?php
global $connection = mysql_conect(....);
include_once 'yourfile.php';
$functionReturnValue = CalledFunction( $para1, $para2 );
?>
现在你的文件.php将看起来像
<?php
function CalledFunetion()
{
global $connection;
// Put rest of the code
}
?>
- 使用mysql_pconnect()函数
:)
使用mysql_pconnect()函数,一切都会好起来的。此函数将重新使用已建立的数据库连接。
编辑1:一个更好的选择是将$connection
作为参数传递给函数,正如Mark所建议的那样。我当然反对使用全局变量,除非真的是必要的。它理所当然地被认为是一种糟糕的编程实践,只会让你头疼。
编辑2:您有三种选择:
-
检查$connect是否为NULL,如果为NULL,则按照Mensur的建议退出并返回错误。如果它不为null,那么您可以通过将$connection作为参数传递给使用数据库的函数,在整个脚本的其余部分中可靠地使用它。
-
再次检查$connect是否为NULL,如果不是,则将其用作函数中的全局变量。我反对这种方法,原因见编辑1。
-
使用
mysql_pconnect()
函数,它将创建一个持久连接,并且任何以后对mysql_pconnect()的调用都将使用相同的连接(如果已建立)。