I am writing my first ever PHP class, trying to learn OO concepts as I go along. The goal of this code is to record a user's IP and related parameters into a database that I might later use as the basis for applying a temporary ban. (No let's not discuss the merits of that strategy - let's keep to coding classes please!). Here's what I have:
class banAss {
public function __construct(mysqli $db){
$this->db = $db;
$this->visitip = $_SERVER['REMOTE_ADDR'];
$this->visitAgent = $_SERVER['HTTP_USER_AGENT'];
$this->visitDate = time();
}
public function addBan(){
$sql = "Insert into banned (visitIP, visitAgent, visitDate,) values (?, ?, ?)";
$stmt = mysqli_prepare($this->db, $sql);
mysqli_stmt_bind_param($stmt, "ssi", $this->visitip, $this->visitAgent, $this->visitDate);
mysqli_stmt_execute($stmt);
mysqli_stmt_close($stmt);
}
}
$banned = new banAss($db);
$banned->addBan();
It's worth noting that I do have a valid database connection that has been opened using mysqli. I have been playing whackamole with the error messages on this. Currently they stand at:
Warning: mysqli_stmt_bind_param() expects parameter 1 to be mysqli_stmt, boolean given in /home/c9/public_html/admin/login.php on line 16
Warning: mysqli_stmt_execute() expects parameter 1 to be mysqli_stmt, boolean given in /home/c9/public_html/admin/login.php on line 17
Warning: mysqli_stmt_close() expects parameter 1 to be mysqli_stmt, boolean given in /home/c9/public_html/admin/login.php on line 18
I don't understand these messages. They suggest perhaps that the 'mysqli_prepare' line that created the variable $stmt messed up somehow, but how?
Warning: mysqli_stmt_bind_param() expects parameter 1 to be mysqli_stmt, boolean given in...
Read closely: it's telling you you're passing in a boolean value when the function doesn't expect it there. mysqli_prepare()
returns a boolean FALSE
when it encounters an error, and that's what you're attempting to pass into the mpsqli_stmt_bind_param()
function, thereby having it produce an error and a boolean FALSE
value, which just trickles down.
Use mysqli_error()
to get the exact error you're getting and possibly a little insight into how to fix said error.
Your query has a syntax error, which means all of the prepare and subsequent calls fail:
$sql = "Insert into banned (visitIP, visitAgent, visitDate,) etc...
^---dangling comma
Never ever assume that a DB operation has succeeded. You need to check for failure, which in your case is a returned value of boolean FALSE:
$stmt = mysqli_prepare(....);
if ($stmt === false) {
... oops something blew up
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.