How do I check mysql db to see if a value exist
<p>So I am trying to check my mysql db if it has a name stored in it that is sent in from form and if it dose not it will be added.  My code I have is not working right and I need some help.</p>

<p>Here is code</p>

<pre><code>try {  
  # MySQL with PDO_MYSQL  
  $DBH = new PDO("mysql:host=$hostname;dbname=$database", $username, $password);  
  $DBH-&gt;setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );

  //$DBH-&gt;prepare('SELECT first FROM contacts');
}  
catch(PDOException $e) { 
    echo "I'm sorry, I'm afraid I can't do that.";  
    file_put_contents('PDOErrors.txt', $e-&gt;getMessage(), FILE_APPEND);   
}
/*$compare = "SELECT * FROM companynames WHERE CompanyNames = :compname";
if ($compare != $compname){
    $query = "INSERT INTO companynames VALUES('$new_id_number','$compname') IF NOT EXISTS";
    mysql_query($query);
    echo "working";
    echo "$state";
}
else
    echo "already inserteed";
mysql_close();*/

$sql = $DBH-&gt;prepare('SELECT COUNT(*) FROM companynames WHERE CompanyNames = :compname');
$sql-&gt;bindParam(':compname', $compname, PDO::PARAM_STR);
$sql-&gt;execute();
echo "tsting"; // works up to here 
if ($res = $conn-&gt;query($sql)) {

    /* Check the number of rows that match the SELECT statement */
  if ($res-&gt;fetchColumn() &gt; 0) {

        /* Issue the real SELECT statement and work with the results */
         $sql = "SELECT CompanyNames FROM companynames WHERE CompanyNames = :compname";
       foreach ($conn-&gt;query($sql) as $row) {
           print "Name: " .  $row['CompanyNames'] . "\n";
         }
    }
    /* No rows matched -- do something else */
  else {
      print "No rows matched the query.";
    }
}
echo "tsting";
$res = null;
$conn = null;
$DBH = null; 
</code></pre>
