PHP错误:为什么此方法不起作用,我无法在页面中看到数据结果?

时间:2019-02-03 14:29:17

标签: php mysqli

我正在设置一个新的wampserver,并使用名为“用户”的表创建了一个新数据库

Apache 2.4.23&PHP 7.1.10&mySQL 5.7.14

<?php

    $server = 'localhost';
    $serverUsername = 'root';
    $serverPassword = '';
    $dbName = 'test';

    $connection = mysqli_connect($server,$serverUsername,$serverPassword);
    msqli_select_db($dbName);
    if(!$connection){
        echo 'connection failed to database '.mysqli_connect_error();
    }
    $sql = "SELECT * FROM users";
    $query = mysqli_query($sql);
    while($row = mysqli_fetch_array($query)){
        print_r($row);
    }

?>

我的价值确实存在于数据库中,但是运行代码后页面中什么都没显示

1 个答案:

答案 0 :(得分:1)

看看有关修复的评论     

$server = 'localhost';
$serverUsername = 'root';
$serverPassword = '';
$dbName = 'test';

// FIX 1
// You need to mention the database name as the last argument
$connection = mysqli_connect($server,$serverUsername,$serverPassword, $dbName);
if(!$connection){
    echo 'connection failed to database '.mysqli_connect_error();
}

$sql = "SELECT * FROM users";

// FIX 2
// The first argument should be your mysqli connection
$query = mysqli_query($connection, $sql);

// Check for errors
if (!$query) {
    printf("Error: %s\n", mysqli_error($connection));
    exit();
}

while($row = mysqli_fetch_array($query)){
    print_r($row);
}

?>

mysqli_connect的引用:https://secure.php.net/manual/en/function.mysqli-connect.php

mysqli_query的引用:https://secure.php.net/manual/en/mysqli.query.php