bickyz Posted February 8, 2015 Share Posted February 8, 2015 Hi, I have following php code that displays data from the mysql tables: <?php $pdo = Database::connect(); $sql = 'SELECT DISTINCT * FROM tblcompany c NATURAL JOIN tblstock s WHERE DATE(updated) = DATE(NOW()) AND updated = (SELECT MAX(_s.updated) FROM tblstock _s WHERE _s.comid = c.comid) ORDER BY stock DESC, updated ASC'; foreach ($pdo->query($sql) as $row) { echo '<tr>'; echo '<td>'. $row['company'] . '</td>'; echo '<td>'. $row['stock'] . '</td>'; echo '</tr>'; } Database::disconnect(); ?> I would like to display the message "no results updated yet" if the query has no results. I have tried adding 'echo "no results updated yet"' after the last line "Database:disconnect ();" but it displays the message whether there is a results or not. How do I display such message. Any help would be much appreciatedm thank you. Quote Link to comment Share on other sites More sharing options...
mac_gyver Posted February 8, 2015 Share Posted February 8, 2015 foreach ($pdo->query($sql) as $row) { ^^^ using this programming style doesn't lend itself to checking if the query matched any rows, nor does it lend itself to using prepared queries and using the same basic program logic for non-prepared and prepared queries. it also ties your presentation logic to the database library being used and it requires that you run the query again should you need to iterate over the result set more than once. i recommend that you not use this programming style and instead fetch the data into a php array variable in your database dependent code, using the pdo ->fetchAll() method in those cases where you expect one or more rows, and using the pdo ->fetch() method when you expect at most only one row. you can then test the size of the array holding the data (see the count() function) to determine how many rows are in it and then use the same basic foreach() loop you have now to loop over the array of data. edit: your code also implies that you are opening a database connection, running one query, then closing the database connection. your application should only open one database connection, then close it only after you have finished using it. Quote Link to comment 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.