我有commFun.php用于commong函数;
<?php
function connectDB(){
$con = @mysqli_connect( "localhost:3306", "root", "P@ssw0rd", "DogSport" ) or die ("Couldn't connect to server");
}
//check that email is not already in list
function emailChecker( $email ){
connectDB();
$safe_email = mysqli_real_escape_string( $con, $email );
$check_sql = "SELECT Id FROM Subscribers WHERE Email='". $safe_email. "'";
$result = mysqli_query ( $con, $check_sql ) or die ("Couldn't execute SELECT query: ". mysqli_error($con));
}
?>
当我从另一个PHP脚本调用emailChecker()函数时,为什么connectDB()中的$ con变量不可用于emailChecker()函数?我已经在emailChecker()函数中调用了connectDB()函数?我究竟做错了什么?????
我收到以下错误;
Notice: Undefined variable: con in C:\xampp\htdocs\PHP\commonFun.php on line 11
Warning: mysqli_real_escape_string() expects parameter 1 to be mysqli, null given in C:\xampp\htdocs\PHP\commonFun.php on line 11
Notice: Undefined variable: con in C:\xampp\htdocs\PHP\commonFun.php on line 14
Warning: mysqli_query() expects parameter 1 to be mysqli, null given in C:\xampp\htdocs\PHP\commonFun.php on line 14
Notice: Undefined variable: con in C:\xampp\htdocs\PHP\commonFun.php on line 14
Warning: mysqli_error() expects parameter 1 to be mysqli, null given in C:\xampp\htdocs\PHP\commonFun.php on line 14
Couldn't execute SELECT query:
答案 0 :(得分:1)
糟糕的解决方案,但它会起作用:
function connectDB(){
global $con;
$con = @mysqli_connect( "localhost:3306", "root", "P@ssw0rd", "DogSport" ) or die ("Couldn't connect to server");
}
//check that email is not already in list
function emailChecker( $email ){
global $con;
connectDB();
$safe_email = mysqli_real_escape_string( $con, $email );
$check_sql = "SELECT Id FROM Subscribers WHERE Email='". $safe_email. "'";
$result = mysqli_query ( $con, $check_sql ) or die ("Couldn't execute SELECT query: ". mysqli_error($con));
}
另一种解决方案:
$con = @mysqli_connect( "localhost:3306", "root", "P@ssw0rd", "DogSport" ) or die ("Couldn't connect to server");
//check that email is not already in list
function emailChecker( $email ){
global $con;
$safe_email = mysqli_real_escape_string( $con, $email );
$check_sql = "SELECT Id FROM Subscribers WHERE Email='". $safe_email. "'";
$result = mysqli_query ( $con, $check_sql ) or die ("Couldn't execute SELECT query: ". mysqli_error($con));
}
在脚本中的每个函数调用中调用mysqli_connect()都很糟糕。每次执行页面时,您必须只连接一次数据库。
答案 1 :(得分:-1)
function connectDB(){
$ con = @mysqli_connect(“localhost:3306”,“root”,“P @ ssw0rd”,“DogSport”)或死亡(“无法连接到服务器”);
返回$ con; }