我想将连接到 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
}
非常感谢!