function question

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
decoy1
Forum Commoner
Posts: 50
Joined: Fri Feb 21, 2003 1:33 pm
Location: St. Louis

function question

Post by decoy1 »

Hi,

I'd like to have a function that simply checks a variable against a db for duplicates. The problem is in the query where I have to pick the table (I think). I'm not getting it to work, and don't know where it is failing. I tried passing the name of the table as a string, and stored in a variable, and nada. This has got to be common, does anyone have any suggestions?

This is a stripped down version of the function I wrote.

Code: Select all

function chkDuplicates($tblName, $var)
{
  $sql = "SELECT * FROM $tblName WHERE name = '$var'";
  $result = mysql_query($sql);
  $num = mysql_numrows($result);
  if($num = '0')
  {
    return true; 
  }
  return false;  
}
Thanks :)
User avatar
phice
Moderator
Posts: 1416
Joined: Sat Apr 20, 2002 3:14 pm
Location: Dallas, TX
Contact:

Post by phice »

Coding:

Code: Select all

<?php
function chkDuplicates($tblName, $var) 
  {
  if(mysql_num_rows(mysql_query("SELECT * FROM $tblName WHERE name = '$var'")) == 0) { return false; } else { return true; }
  }
?>
Usage:

Code: Select all

<?php
if (chkDuplicates("table1", "phice")) {
echo "No duplicates.";
} else {
echo "Found a duplicate of 'phice'.";
}
?>
*saves function* Great idea for this function. :)
Image Image
decoy1
Forum Commoner
Posts: 50
Joined: Fri Feb 21, 2003 1:33 pm
Location: St. Louis

Post by decoy1 »

Right on... thanks Phice :D
Post Reply