Jump to content

If entry already exists


Mutley

Recommended Posts

I'm trying to do an IF statement to check if an entry already exists, if it doesn't continue with submitting data, if it does, come up with an error message, how would I do this?

I have my INSERT INTO sql statement and the $_POST variables listed. Do I put the IF Statement before the INSERT INTO? How do I check the database though?
Link to comment
https://forums.phpfreaks.com/topic/33754-if-entry-already-exists/
Share on other sites

Here is the code:

[code]

        $this = $_POST['this'];
$that = $_POST['that'];

$sql  = "INSERT INTO `data` ";
$sql .= "(this, that) ";
$sql .= "VALUES ";
$sql .= "('".$this."', '".$that."')";

mysql_query($sql);
$profile_id = mysql_insert_id();

echo "<b>Data inserted! </b><br /><br />";
echo "<a href=index.php>Click here to continue</a>";
exit();
}
else {

// Form below
[/code]

So what I want to do is something like

if($this ...already exists) {
echo "Sorry that already exists."
} else {
......Insert date
[quote]Do I put the IF Statement before the INSERT INTO[/quote]

Yes.

An example.

[code]
<?php
 if (isset($_POST['data'])) {
   // connect to db.
   $sql = "SELECT data FROM tbl WHERE data = '{$_POST['data']}';"
   if ($result = mysql_query($sql)) {
     if (!mysql_num_rows($result)) {
       $sql = "INSERT INTO tbl (data) VALUES ('{$_POST['data']}');"
       if (mysql_query($sql)) {
         echo "insert complete";
       }
     } else {
       echo "data already exists";
     }
   }
 }
?>
[/code]
Connect to the db and run a query to check the information you want.
[code]
<?php
$query="SELECT * FROM table WHERE field='$comparision_variable";
$result=mysql_query($query);

if(mysql_num_rows($result > 0)){

// condition is true and this already exists, skip it

}else{
// mysql_num_rows($result) is not greater, than 0 so it does not exist... insert data now
$query="INSERT INTO table blah blah blah";
$result=mysql_query($query);
}
?>
[/code]

AHHH Thorpe, you are faster (and better)than me.. I was typing when you posted yours.. curse you  ;)
[quote author=mgallforever link=topic=121951.msg502305#msg502305 date=1168529434]
[quote author=chronister link=topic=121951.msg502296#msg502296 date=1168528712]
if(mysql_num_rows($result > 0)){
[/quote]

That wouldn't work. mysql_num_rows($result) > 0
[/quote]

dumb fat fingers..... ;D

fingers were faster than my brain.

Nate

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.