我想将用于连接mysql的代码放在PHP的单独函数中,然后在其他函数中使用该函数。令人惊讶的是,我无法找到有关如何做到这一点的在线资源。我想做这样的事情:
function connect_mysql() {
$con = mysqli_connect("localhost", "root", "somepass", "testdb");
if (mysqli_connect_errno($con)) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
return $con;
}
function some_function() {
connect_mysql();
// and use that connection here
//so that I don't have to retype connection code again
}
非常感谢!
答案 0 :(得分:2)
我会按照以下方式执行此操作,使用connect_mysql
内的static variable,因此只创建了一个MySQL连接:
function connect_mysql() {
static $con = null;
if ($con == null) {
$con = mysqli_connect("localhost", "root", "somepass", "testdb");
if (mysqli_connect_errno($con)) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
return null;
}
}
return $con;
}
function some_function() {
$con = connect_mysql();
$con->prepare(...);
}
的示例
答案 1 :(得分:0)
两人认为要考虑:
(1)如果你想继续你的函数some_function()
中的对象,那么为它使用一个变量:
示例:
function some_function() {
$my = connect_mysql();
$my->query('some great sql query...');
}
(2)要改进连接函数connect_mysql()
,只要连接失败,就应该以定义的状态退出它,可能是这样的:
function connect_mysql() {
$con = mysqli_connect("localhost", "root", "somepass", "testdb");
if (mysqli_connect_errno($con)) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
return false; // <- exit here....
}
return $con;
}
这不一定是必需的,但它可以帮助您检测功能之外的问题,并在代码变大时维护代码。