Reputation: 731
I am trying to write an IP ban. The users IP is stored in the database. I can manually add that users IP to the banlist. Unfortunately, the following code doesn't work. I think the problem is in getting the array out of the db.
$ip = $_SERVER['REMOTE_ADDR'];
$bannedips = array();
$notBanned = true; //later used to check, if ip is banned
$sql = "SELECT ip FROM ipban";
$result = mysqli_query($conn, $result);
while($row = mysql_fetch_array($result, MYSQL_NUM)){
$bannedips[] = $row;
}
if (in_array($ip, $bannedips)) {
$notBanned = false;
}
Upvotes: 0
Views: 2839
Reputation: 7791
Just change:
while($row = mysql_fetch_array($result, MYSQL_NUM)){
$bannedips[] = $row;
And you can't merge mysqli function with mysql
$result = mysqli_query($conn, $result);
while($row = mysql_fetch_array($result, MYSQL_NUM)){
finally (EDIT):
$host = "example";
$username = "example";
$password = "example";
$database = "example";
$ip = $_SERVER['REMOTE_ADDR'];
$bannedips = array();
$notBanned = true; //later used to check, if ip is banned
$connection = new mysqli($host, $username, $password, $database);
$query = $connection->query("SELECT ip FROM ipban");
while ($row = $query->fetch_array()) {
$bannedips[] = $row['ip'];
}
if (in_array($ip, $bannedips)) {
$notBanned = false;
}
You can read more at:
Upvotes: 1
Reputation: 2309
Instead of query all entries you should search just the ip for performance reason
$ip = $_SERVER['REMOTE_ADDR'];
$notBanned = true; //later used to check, if ip is banned
$sql = "SELECT ip FROM ipban WHERE ip = ?";
if ($stmt = mysqli_prepare($conn, $sql)) {
/* bind parameters for markers */
mysqli_stmt_bind_param($stmt, "s", $ip);
if($result = mysqli_query($conn, $sql)){
$notBanned = false;
mysqli_free_result($result);
}
}
Object oriented style should be:
$mysqli = new mysqli(/* Whatever needed to establish connection */);
$ip = $_SERVER['REMOTE_ADDR'];
$notBanned = true; //later used to check, if ip is banned
$sql = "SELECT ip FROM ipban WHERE ip = ?";
if ($stmt = $mysqli->prepare($sql)){
$stmt->bind_param("s", $ip);
$stmt->execute();
if($stmt && $stmt->num_rows > 0){
$notBanned = false;
}
}
Upvotes: 2
Reputation: 40
The issue is held inside of your while loop. Whilst appending the data to your $bannedips array, you're forgetting to select the zeroth (ip column) key from the $row array.
Change $row to row[0] like so:
while($row = mysql_fetch_array($result, MYSQL_NUM)){
$bannedips[] = $row[0];
}
Upvotes: 0