You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP7.2.24出现Call to undefined function mysqli_connect()错误求助

解决 "Call to undefined function mysqli_connect()" 错误及代码安全优化

Hey there! Welcome to Stack Overflow 😊 Let's break down how to fix your error first, then go over some important security improvements for your login code.

错误原因

The error Call to undefined function mysqli_connect() means your PHP 7.2 installation on Ubuntu 18.04 doesn't have the mysqli extension installed or enabled. This extension is required to connect to MySQL databases using the mysqli functions.

修复步骤

Follow these steps to get the extension set up:

  1. Install the mysqli extension for PHP 7.2:
    sudo apt-get update && sudo apt-get install php7.2-mysqli
    
  2. Restart Apache to apply the changes:
    sudo systemctl restart apache2
    
  3. Verify the extension is enabled:
    Create a file named phpinfo.php in /var/www/html/ with this content:
    <?php phpinfo(); ?>
    
    Access it via your browser (e.g., http://your-server-ip/phpinfo.php) and search for "mysqli"—you should see a section confirming the module is active.

代码安全优化(非常重要!)

Your current login code has critical security flaws that could let attackers access your database. Here's how to fix them:

  • SQL Injection Risk: Never directly insert user input into SQL queries. Use prepared statements instead.
  • Redundant Code: You already specified the database in mysqli_connect(), so mysqli_select_db($a,$db); is unnecessary.
  • Plaintext Passwords: Storing passwords as plain text is a huge security risk. Always hash passwords with password_hash() when saving them, and verify with password_verify().

优化后的代码示例

<?php
$host = "localhost";
$user = "root";
$password = "";
$db = "demo";

// 建立数据库连接并检查错误
$conn = mysqli_connect($host, $user, $password, $db);
if (!$conn) {
    die("数据库连接失败: " . mysqli_connect_error());
}

// 检查POST参数是否存在
if (isset($_POST['username'], $_POST['password'])) {
    $username = $_POST['username'];
    $inputPassword = $_POST['password'];

    // 使用预处理语句防止SQL注入
    $query = "SELECT * FROM demo WHERE User = ? LIMIT 1";
    $stmt = mysqli_prepare($conn, $query);
    mysqli_stmt_bind_param($stmt, "s", $username);
    mysqli_stmt_execute($stmt);
    $result = mysqli_stmt_get_result($stmt);

    if ($userData = mysqli_fetch_assoc($result)) {
        // 验证密码(确保数据库中存储的是password_hash生成的哈希值)
        if (password_verify($inputPassword, $userData['Pass'])) {
            echo "You Have Successfully Logged in";
        } else {
            echo "You Have Entered Incorrect Password";
        }
    } else {
        echo "You Have Entered Incorrect Username or Password";
    }

    // 关闭预处理语句
    mysqli_stmt_close($stmt);
}

// 关闭数据库连接
mysqli_close($conn);
?>

内容的提问来源于stack exchange,提问作者kaiwen_

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.06 16:04:10