繁体   English   中英

如何使用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);

第一点:

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

第三点

$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。

您可以使用它。

$row=mysqli_fetch_row($result)

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

希望这会有所帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM