简体   繁体   English

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

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

Here is an example of the current PHP code I have. 这是我当前拥有的PHP代码的示例。 I simply want to grab one row from the table, but it returns this error: 我只想从表中获取一行,但它返回此错误:

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

Any insight would be appreciated. 任何见识将不胜感激。

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

Point 1 : 第一点:

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

Point 2: 第2点:

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

Point 3: 第三点

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

here is a full 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();

You can use 您可以使用

$row=mysqli_fetch_array($result)

You don't even have to use while since you wanna fetch only one row. 由于您只想获取一行,因此您甚至不必使用任何时间。 IF you wanna fetch more than one row, then you can use the while. 如果您想获取多个行,则可以使用while。

You can use this. 您可以使用它。

$row=mysqli_fetch_row($result)

It will fetches the one row from result set.. 它将从结果集中获取一行。

Hope this will help.! 希望这会有所帮助。

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

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