davidolson Posted June 8, 2013 Share Posted June 8, 2013 if i delete this code everything works $number_of_rows = $completed_offer_stmt->fetch(PDO::FETCH_COLUMN); if (!$number_of_rows){ print "No results"; } $query_1 = "SELECT * FROM offer_pending WHERE status = 1 ORDER BY date_modified DESC LIMIT 10"; $completed_offer_stmt = $dbh->prepare($query_1); $completed_offer_stmt->execute(); $number_of_rows = $completed_offer_stmt->fetch(PDO::FETCH_COLUMN); if (!$number_of_rows){ print "No results"; } while($completed_offer = $completed_offer_stmt->fetch(PDO::FETCH_ASSOC)){ $query_2 = "SELECT * FROM offers WHERE id= :completed_offer_id"; $offers_stmt = $dbh->prepare($query_2); $offers_stmt->bindParam(':completed_offer_id', $completed_offer['offer_id']); $offers_stmt->execute(); $offers = $offers_stmt->fetch(PDO::FETCH_ASSOC); print "{$offers['name']} {$offers['points']}"; } Quote Link to comment https://forums.phpfreaks.com/topic/278933-need-help-wont-display-database-first-result/ Share on other sites More sharing options...
mac_gyver Posted June 8, 2013 Share Posted June 8, 2013 (edited) to test if a PDO query that executed without any errors returned any rows at all, use the ->columnCount() method (a zero means no result set since you cannot select nothing/no-columns in a query.) if you are going to actually use all the rows a query returned, but you also want to test if there are/are-not any rows, just use the ->fetchAll() method and use count() to determine how many rows there are. Edited June 8, 2013 by mac_gyver Quote Link to comment https://forums.phpfreaks.com/topic/278933-need-help-wont-display-database-first-result/#findComment-1434844 Share on other sites More sharing options...
DavidAM Posted June 8, 2013 Share Posted June 8, 2013 Well, then, delete that code. It's wrong anyway. ->fetch retrieves a row from the database. It does NOT retrieve the record count. So, with that code you are retrieving the first row. Then you start your loop by retrieving the NEXT row, but you have never processed the first one. Note: The reason prepared statements were invented (many years ago) was to speed up processing when running queries in a loop. But to benefit from that, you would PREPARE the statement OUTSIDE of the loop. HOWEVER, in this case (as in most cases) you can and should get all of the data in your first query using a JOIN. Quote Link to comment https://forums.phpfreaks.com/topic/278933-need-help-wont-display-database-first-result/#findComment-1434845 Share on other sites More sharing options...
davidolson Posted June 8, 2013 Author Share Posted June 8, 2013 Changed the ->fetch(PDO::FETCH_COLUMN); to ->rowCount(); and everything works Quote Link to comment https://forums.phpfreaks.com/topic/278933-need-help-wont-display-database-first-result/#findComment-1434870 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.