如何使用 php 从 mySQL table 获取一行数据?

How do I get one row of data from mySQL table using php?

这是我现有的 PHP 代码的示例。我只是想从 table 中抓取一行,但 returns 这个错误:

Call to a member function fetch_assoc() on a non-object

如有任何见解,我们将不胜感激。

$pathname = "C:\Users\BL\Documents\GitHub\Moozik\music";
$files = scandir($pathname);
$server = "localhost";
$user = "root";
$pass = "";

while ($files[0] == "." || $files[0] == "..") {
    array_shift($files);
}

print_r($files);
$song = $pathname . '\' . $files[0];

$conn = new mysqli($server, $user, $pass);

if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 

$sql = "SELECT song_path FROM song_data";
$result = mysqli_query($conn, $sql);

while($row = $result->fetch_assoc()) {
    $its = $row["song_path"];
    printf($its);
}

mysqli_close($conn);

您可以使用

$row=mysqli_fetch_array($result)

您甚至不必使用 while,因为您只想获取一行。如果你想获取多行,那么你可以使用 while。

你可以用这个。

$row=mysqli_fetch_row($result)

它将从结果集中获取一行..

希望这会有所帮助!

第 1 点:

You have mixed mysqli Object-oriented and Procedural methods...Use any one

第 2 点:

$conn = new mysqli($server, $user, $pass); 
// Here You missed database to be selected

第 3 点:

$result = mysqli_query($conn, $sql); // Used procedural method But Connection is by Object Oriented method

这是一个完整的面向对象的方法

$conn = new mysqli($server, $user, $pass, $database);

if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 

$sql = "SELECT song_path FROM song_data";
$result = $conn->query($sql);

while($row = $result->fetch_assoc()) {
           $its = $row["song_path"];
            echo $its;
    }


$conn->close();