Forum Moderators: coopster

Message Too Old, No Replies

Checking for existing data...

How to check before righting if something exists.

         

kickatruckxxx

8:40 pm on Mar 16, 2004 (gmt 0)

10+ Year Member



Im working on a DVD databasing system for a project, and was trying to write a simple piece of code that would check if a Title, or Actor, or Director, blah blah existed before adding them to the table. IE to avoid duplication.

Here is what I wrote:

$query = "SELECT * FROM $type ";
$query .= "WHERE name = $person";
$results = mysql_query($query);
$name = mysql_result($results, 0);
if ($person == $name) {
header("Location: add_form_person.php?message=$person already exists in database");
exit();
}

Frankly, I thought if I searched the table ($type) for the actor ($person) I could use the results to compare with the original and if it was the same, it would exit.

Is there a way to return 'TRUE' if the query finds anything at all. The way I wrote it gives me errors, stating it is an invalid request arguement. Any suggestions...

Timotheos

9:17 pm on Mar 16, 2004 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Hey there,

Check this thread out...
[webmasterworld.com...]

You're basically going to use mysql_num_rows to see if your select statement returns anything. If it does then exit out.

Your error is probably because you need single quotes around your where variable.
$query .= "WHERE name = '$person'";
Especially true if you have first and last names in $person like 'Robert Redford' otherwise the space will throw an error.

slade7

9:47 pm on Mar 16, 2004 (gmt 0)

10+ Year Member



$results = mysql_query("SELECT COUNT(*)
FROM $type
WHERE name = '$person'");

$name = mysql_result($results,0);

if ($name > 0) {
header("Location: add_form_person.php?message=$person already exists in database");
exit();
}

With this the query will either return a number or 0 - if your name field is unique, then it will return 1 or 0 and you can act accordingly.

you might need to single quote '$type' if you are using a variable for a table name... I haven't done this in a long time.

ergophobe

10:26 pm on Mar 16, 2004 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



Perhaps you've already thought about this, but the hard part with such a database is not preventing an identical name from being re-entered, it is preventing multiple names for the same person.

You need to have a method for making sure that you don't end up with a database full of movies by

Bob Redford
R. Redford
Redford, Robert (i.e. someone interposes first and last name on entry form)
Robert Refdord
Robret Redford

and so forth.

kickatruckxxx

7:28 pm on Mar 17, 2004 (gmt 0)

10+ Year Member



Thank you... i think i will try slades suggestion, but that you everyone for your thoughts. I knew i forgot something in the query itself. And im positive the single quotes will fix it. Thanks again...