如何使用 php 从 mySQL 表中获取一行数据


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

这是我拥有的当前PHP代码的示例。我只想从表中抓取一行,但它返回此错误:

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);

第 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();
您可以使用

$row=mysqli_fetch_array($result)

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

你可以

使用它。

$row=mysqli_fetch_row($result)

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

希望这会有所帮助。!