SitePoint Sponsor

User Tag List

Results 1 to 2 of 2
  1. #1
    SitePoint Enthusiast
    Join Date
    Sep 2000
    Posts
    27
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    SELECT 1 row: PHP/MySQL

    This has been on my mind...

    I have always used this (for the most part) to select data in a DB...

    Code:
    $connection = mysql_connect($hostname, $user, $pass) or die ("Unable to connect!");
    $query = "SELECT * from $table.......";
    $result = mysql_db_query($database, $query, $connection) or die ("Could not execute query: $query. " . mysql_error());
    while(list($id, $name, $address, $city,.......) = mysql_fetch_row($result))
     { 
     
     // display data
     
     }
    Now, if I only want to SELECT one row of data (ie. WHERE id='123') is the above still efficient (or 'good coding') to use? If not, what is the better method.

    Thanks,
    Andrew

  2. #2
    SitePoint Zealot
    Join Date
    Aug 2002
    Posts
    168
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    try this...

    You could do it this way..

    PHP Code:
     
    function dbConnect()
    {
     var 
    $dbConnection mysql_connect($hostname$user$pass);    
     if (
    $dbConnection)
     {
      
    mysql_select_db ($dbName$dbConnection);
      return 
    $dbConnection;
     }
     else return 
    false;
    }
    // The above code could sit in an include file.
    // You can set up some routine to check the connection works like
    // $db = dbConnect();
    // if (!$db) echo 'Lookout the database connection is dead!';
    // but assuming it works you can just do this whenever needed
    $db dbConnect();
    // You should avoid using the 'All' operator (*) for speed of execution
    // instead, call the individual field names. You should also try to avoid using 
    // variables inside double quotes ("$table"), instead use concatanated 
    // single quote strings ('. $table .')
    $selectStatment 'SELECT field1, field2, field3 FROM '$table .' WHERE id=123';
    $recordset mysql_query($selectStatment$db);
    // If you know that it will only return one row then you can go...
    $rowArray mysql_fetch_row($recordset);
    echo 
    $rowArray[0] .' | '$rowArray[1] .' | '$rowArray[2];
    // otherwise you could do a loop like this...
    while ($rowArray == mysql_fetch_row($recordset))
    {
     echo 
    $rowArray[0] .' | '$rowArray[1] .' | '$rowArray[2] .'<br>';

    I hope this helps. This is only one way of doing this, there is another ten different ways it could be done so have a search around, you never know what you might find under some rock!

    bye


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •