php - 如何使用 mysqli_fetch_array 从 MySQL 列中获取数组

标签 php mysql sql arrays mysqli

我正在尝试编写 IP 禁令。用户IP存储在数据库中。我可以手动将该用户 IP 添加到黑名单。不幸的是,下面的代码不起作用。我认为问题在于从数据库中获取数组。

$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;
}

最佳答案

出于性能原因,您应该只搜索 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);
    }
}

面向对象的风格应该是:

$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;
    }
}

关于php - 如何使用 mysqli_fetch_array 从 MySQL 列中获取数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28799194/

相关文章:

php - MySQL 服务器安装时间过长

mysql - 用 MySQL 中的另一个表更新表

sql - 更改查询以避免 Bigquery 中的 "Aggregations of aggregations are not allowed"

sql - 如何理解 postgres EXPLAIN 输出

php - 如何在 Laravel 上检查 Debug模式

php - MySQL SELECT 语句只返回一行

php - 翻译我主题的 function.php 文件中的自定义标签字段

php - 从复选框获取多个值并将其存储在 DB php 中

php - 如何从不同的数据库中获取数据并将其保存到另一个数据库中

mysql - 为什么 column = upper(column) 在 Oracle 中有效而在 MySQL 中无效?