Jump to content

Recommended Posts

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.

 

 

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.

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.