views:

130

answers:

2

Ok, I have a database full of values with one field value for prospects and another for clients...

I'd like to retrieve only the clients information...

How do I write the function???

UPDATE

Here is the script I tried to write:

<?php 
    try { 
     $sql = "SELECT * FROM clients" // WHERE history" or die(mysql_error()); 

     foreach ($dbh->query($sql) as $row) { 
      $row['history'] = $value; 

      if ($value == 'clients'){   
       echo "1212"; 
      } else { 
       echo "Failed"; 
       return; 
      } 
     } 

     $dbh = null; 
    } catch (PDOException $e) { 
     echo "Failed: " . $e->getMessage(); 
     $dbh->rollback(); 
    }
?>
A: 

Based on your sample script this would do the same but it would place the conditional operator in the query at the database layer instead of within the script at the application layer:

<?php 
    try { 
     $sql = "SELECT * FROM clients WHERE history = 'clients'" // WHERE history" or die(mysql_error()); 

     foreach ($dbh->query($sql) as $row) {       
      echo "1212";  
     } 

     $dbh = null; 
    } catch (PDOException $e) { 
     echo "Failed: " . $e->getMessage(); 
     $dbh->rollback(); 
    }
?>

Of course, it obviously won't reflect non-client rows like your sample did, but from what I could understand of your question this was what you actually wanted to have happen.

Noah Goodrich
+1  A: 

There's no reason to do a rollback here, especially since you haven't started a transaction, and this is just a SELECT, so there's nothing to rollback ... I'm also not sure why you're nulling out $dbh. It's possible to reuse $dbh for other queries, or throughout your application...

Also, your select statement should reflect what data you actually need. If all you need is history, then SELECT history FROM clients[...] is best.

<?php 
try { 
    $sql   = "SELECT * FROM clients WHERE history = 'clients'"; 
    $query = $dbh->prepare($sql);

    $query->execute();

    while($row = $query->fetch())
    {
      if($row['history'] == 'clients'){
        echo '1212';
      }
    }
} catch (PDOException $e) { 
    echo "Failed: " . $e->getMessage(); 
}
?>
Josh Boyd
Just to note, you can add LIMIT 1 at the end of the query if you only want one response.
Gus