[英]How get an array from a MySQL column with mysqli_fetch_array
I am trying to write an IP ban. 我正在尝试撰写IP禁令。 The users IP is stored in the database.
用户IP存储在数据库中。 I can manually add that users IP to the banlist.
我可以将该用户IP手动添加到黑名单中。 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;
}
Instead of query all entries you should search just the ip for performance reason 而不是查询所有条目,您应该只搜索ip以获得性能原因
$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;
}
}
Just change: 只是改变:
while($row = mysql_fetch_array($result, MYSQL_NUM)){
$bannedips[] = $row;
And you can't merge mysqli function with mysql 而且您无法将mysqli函数与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: 您可以在以下位置阅读更多信息:
http://php.net/manual/en/function.mysql-fetch-array.php
http://php.net/manual/zh/function.mysql-fetch-array.php
The issue is held inside of your while loop. 该问题保存在您的while循环内。 Whilst appending the data to your $bannedips array, you're forgetting to select the zeroth (ip column) key from the $row array.
在将数据追加到$ bannedips数组的同时,您忘记了从$ row数组中选择第零个(ip列)键。
Change $row to row[0] like so: 将$ row更改为row [0],如下所示:
while($row = mysql_fetch_array($result, MYSQL_NUM)){
$bannedips[] = $row[0];
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.