Fatal error: Class 'TableRows' not found i

2020-05-06 08:22发布

问题:

I got an error like this

Fatal error: Class 'TableRows' not found in /Applications/XAMPP/xamppfiles/htdocs/colorlib-search-23/test.php on line 15

Here is my code :

$servername = "localhost";
$username = "root";
$password = "";
$dbname = "test";

try {
    $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $stmt = $conn->prepare("SELECT * FROM users"); 
    $stmt->execute();

    // set the resulting array to associative
    $result = $stmt->setFetchMode(PDO::FETCH_ASSOC); 
    foreach(new TableRows(new RecursiveArrayIterator($stmt->fetchAll())) as $k=>$v) { 
        echo $v;
    }
}
catch(PDOException $e) {
    echo "Error: " . $e->getMessage();
}
$conn = null;

Checked names of the database table and all, copy-pasted other code but still it's not working

$servername = "localhost";
$username = "root";
$password = "";
$dbname = "test";

try {
    $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $stmt = $conn->prepare("SELECT * FROM users"); 
    $stmt->execute();

    // set the resulting array to associative
    $result = $stmt->setFetchMode(PDO::FETCH_ASSOC); 
    foreach(new TableRows(new RecursiveArrayIterator($stmt->fetchAll())) as $k=>$v) { 
        echo $v;
    }
}
catch(PDOException $e) {
    echo "Error: " . $e->getMessage();
}
$conn = null;

This error should not come.

回答1:

There is a certain extremely harmful article on the Internet telling that you need whatever TableRows class to work with PDO. Which is extremely rubbish.

In reality you don't need anything like this. Just use a regular foreach

$servername = "localhost";
$username = "root";
$password = "";
$dbname = "test";

$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->query("SELECT * FROM users"); 
$data = $stmt->fetchAll(PDO::FETCH_ASSOC);

At this point you have a conventional PHP array that can be iterated over as any other array using foreach or encoded using json_encode or used any other way

// iterate over rows
foreach($data as $row) { 
    // iterate over values in each row
    foreach($row as $v) { 
        echo $v, " ";
    }
    echo "<br>"\n;
}


标签: php mysql pdo