简体   繁体   中英

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

Here is an example of the current PHP code I have. 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:

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

You can use this.

$row=mysqli_fetch_row($result)

It will fetches the one row from result set..

Hope this will help.!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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