1. when learning php, use the PDO mode to connect to the database. When querying data, an error occurs when the fetch method is called: Fatalerror: Calltoamemberfunctionfetch () onanon-object2. code {code ...} 3. error Result 4. database
1. When learning php, connect to the database in PDO mode. When querying data, an error occurs when the fetch method is called: Fatal error: Call to a member function fetch () on a non-object
2. Code
// PDO connection to the database try {$ db_conn = new PDO ('mysql: host = localhost; dbname = test', 'root', '123'); echo "connection successful! ";} Catch (PDOException $ e) {echo" cocould not connect to datebase ";} // SELECT data FROM the table $ stmt = $ db_conn-> query ('select * FROM user'); var_dump ($ stmt ); // display the result while ($ row = $ stmt-> fetch () {echo $ row ['name']. $ row ['number']. $ row ['class'];}
3. error results
4. Database
Reply content:
1. When learning php, connect to the database in PDO mode. When querying data, an error occurs when the fetch method is called: Fatal error: Call to a member function fetch () on a non-object
2. Code
// PDO connection to the database try {$ db_conn = new PDO ('mysql: host = localhost; dbname = test', 'root', '123'); echo "connection successful! ";} Catch (PDOException $ e) {echo" cocould not connect to datebase ";} // SELECT data FROM the table $ stmt = $ db_conn-> query ('select * FROM user'); var_dump ($ stmt ); // display the result while ($ row = $ stmt-> fetch () {echo $ row ['name']. $ row ['number']. $ row ['class'];}
3. error results
4. Database
Your SQL query has an error. $ stmt is false. How can I execute fetch?
foreach ($db_conn->query('SELECT * FROM user') as $row) { print $row['name'] . "\t"; print $row['age'] . "\t"; }
Reference manual. Generally, the problem can be solved. :)
After the query executes the SQL statement, you can directly use fetchAll to obtain the result set, so that you do not need to read the results one by one in a while loop:
query($sql)->fetchAll(PDO::FETCH_ASSOC) );
You can run the SQL statement you want to query in phpmyadmin,
SELECT * FROM user, it may be wrong.
I have always found errors like this, hoping to help you.