我认为由于某种原因,$ con没有填满连接,或者db_connection()没有正确返回$ con,因为我总是最终得到这个通知:
注意:未定义的变量:con in ...
我也得到了这个错误:
警告:mysqli_query()要求参数1为mysqli,在...中给出null
function db_connection(){
$username="username123";
$password="password1234";
$database="iptracker";
$con=mysqli_connect('localhost',$username,$password,$database);
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
return $con;
}
function add_ip_to_db($user_ip){
//mysqli_close($con);
db_connection();
$current_time = date ('Y-m-d h:m');
mysqli_query($con,"INSERT INTO ips (ip, submit_count, date_time)
VALUES ('". $user_ip ."', 1, $current_time)");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysqli_close($con);
}
function add_count_to_db($user_ip){
//mysqli_close($con);
db_connection();
mysqli_query($con,"UPDATE ips ".
"SET submit_count = submit_count+1 ".
"WHERE ip = '". $user_ip ."'" );
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysqli_close($con);
}
function check_ip($user_ip){
db_connection();
$result = mysqli_query($con,"SELECT * FROM ips WHERE ip='". $user_ip."' LIMIT 1");
if(mysqli_fetch_array($result) !== false){
//Adding record to database
add_ip_to_db($user_ip);
} else {
//Update database and adding another count to 'submit_count'
add_count_to_db($user_ip);
}
}
check_ip($_SERVER['REMOTE_ADDR']);
答案 0 :(得分:0)
您没有使用退回的$con
,请在所有功能中执行此操作:
$con = db_connection();
答案 1 :(得分:0)
您正在调用db_connection函数,该函数返回$ con处理程序,但您没有将它的返回值赋给变量。
尝试修改:
$con = db_connection();
此外,这个$ con赋值也在一个函数内,这意味着该变量只能在该函数的范围内使用。
答案 2 :(得分:0)
那是因为$ con是空的。它是函数的本地。一旦功能结束,它就无处可寻。将变量分配给db_connection();
$con = db_connection();