using php to check data in a database before entering it

I know this is a beginner’s question, but I am a bit stuck at the moment. I am trying to make a record-storing database by using php to connect to a mysql database. I am able to connect and store the data, but what I really want to do is to add something that will check to see if the data has already been entered before inserting the record. Is there an easy way to do this?

BTW, I do know mysql is depreciated. But due to project restrictions, I have to use MYSQL. So, no MYSQLi I posted the code below.

[php]?php

//This is the directory where images will be saved
$target = “files/”;
$target = $target . basename( $_FILES[‘photo’][‘name’]);

//postThis gets all the other information from the form
$tfid=$_POST[‘tfid’];
$fname=$_POST[‘fname’];
$lname=$_POST[‘lname’];
$file=($_FILES[‘photo’][‘name’]);
//-----------------------------------------------------------------------------------------------------------------

$username =
$password =
$hostname =
$database =

//connection to the database
$dbhandle = mysql_connect($hostname, $username, $password)
or die(“Unable to connect to MySQL”);
echo “Connected to MySQL
”;

//select a database to work with
$selected = mysql_select_db("$database",$dbhandle)
or die(“Could not select database crfh_db”);
echo "connected to DATABASE
";

//

//Writes the information to the staff table
mysql_query(“INSERT INTO staff
(tfid, fname, lname)
VALUES (’$tfid’, ‘$fname’, ‘$lname’)”)
or die(mysql_error());

//Writes the information to the pic table
mysql_query(“INSERT INTO pic
(tfid, file)
VALUES (’$tfid’, ‘$file’)”)
or die(mysql_error());

//Writes the photo to the server
if(move_uploaded_file($_FILES[‘photo’][‘tmp_name’], $target))
{

//Tells you if its all ok
echo “The file has been uploaded and your information has been added to the directory”;
}
else {

//Gives an error if its not
echo “Sorry, there was a problem uploading your file.”;
}

?> [/php]

Well you would just do a SELECT before your INSERT and see if any rows are returned.

For example

[php]
$res = mysql_query(“SELECT tfid FROM staff WHERE tfid = " . $tfid . " LIMIT 1”);
$num_rows = mysql_num_rows($res);

if ($num_rows === 0) {
mysql_query(“INSERT INTO staff (tfid, fname, lname) VALUES (’$tfid’, ‘$fname’, ‘$lname’)”)or die(mysql_error());
}
[/php]

Sponsor our Newsletter | Privacy Policy | Terms of Service