• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 154
  • Last Modified:

PHP Database 1 Row Only

Hi

I know how to loop through the results of a database query and build a string based on the results like so:

function getdata($querystring)
{
      $connection = mysql_connect('servername', 'password', '') or die (mysql_error());
      $db = mysql_select_db('databasename', $connection) or die (mysql_error());
      $query = "select * from table where col1 = '".$querystring."'";
      $result = mysql_query($query) or die (mysql_error());
            
      $the_title = '';
      while ($row = mysql_fetch_array($result))
      {
            extract($row);

            $the_data = $the_data."<div class='newsdate'>$new_date</div>";
            $the_data = $the_data."<div class='newssubject'><a href='pdfs/news/$file_name' title='Download $description PDF'><img src='images/pdficon_small.gif' alt='PDF' width='17' height='17' /> $description</a></div>";
            $the_data = $the_data."<div class='clear'></div>";
      }            
      mysql_close($connection);
      
      return $the_data;
}

but what if the query ALWAYS returns 1 row.  I don't see the point in doing a loop.  So is there a better way of returning the results without doing a loop?
0
narmi2
Asked:
narmi2
2 Solutions
 
hernst42Commented:
instead of the while just use for that case:
            $row = mysql_fetch_array($result);
            extract($row);

            $the_data = "<div class='newsdate'>$new_date</div>";
            $the_data = $the_data."<div class='newssubject'><a href='pdfs/news/$file_name' title='Download $description PDF'><img src='images/pdficon_small.gif' alt='PDF' width='17' height='17' /> $description</a></div>";
            $the_data = $the_data."<div class='clear'></div>";


But why not keep the loop, it works also and does not really cost much cpu-time and wotk if you get more than one record accidently.
0
 
psimationCommented:
if you KNOW there will/can only be one row returned in the result (for instance if you have an ID field that is unique and auto_increment and your query had a "where id = x"), then you can simply do this instead of the loop:

$row = mysql_fetch_array($result))
extract($row);

0

Featured Post

Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now