Skip to content
Advertisement

Do Not Duplicate VALUE if already exist on MySQL

I’ve been trying to accomplish this, but as other issues I just can’t figured it out. I’ve been reading around for posibles solutions but non of them goes along with my code, or if they do I can’t figure out how or where to use them.

I have a DB where a user sends records. The database consist in few tables containing the Following “Name, Lastname, Phone“. If any of this values is duplicate, I would like my code to identify and Ignore the submission of the Form if ALL this VALUES already exist on the DB.

Here is my code:

        <?php

        $con = mysql_connect("HOST","USER","PASS");
        if (!$con)
          {
          die('Could not connect: ' . mysql_error());
          }

        mysql_select_db("testdb", $con);
        $sql="INSERT INTO people (Name, LastName, Phone)
        VALUES
        ('$_POST[Name]','$_POST[LastName]','$_POST[Phone]')";

        if (!mysql_query($sql,$con))
          {
          die('Error: ' . mysql_error());
          }
        
        echo "Record Added";

        mysql_close($con);
        ?>

Advertisement

Answer

The mysql_* function are all deprecated now, and should NEVER be used. change your code to do something like the following:

//Set up a PDO connection to MySQL
$host = 'host_name';
$dbname = 'database_name';
$user = 'user_name';
$pass = 'user_pass';
try
{
    $DB = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass); 
}
catch(PDOException $e)
{  
    echo $e->getMessage();  
}

//Determine whether the appropriate values have been passed.
if(isset($_POST['Name']))
{
    $name = $_POST['Name'];
}
else
{
    echo "You must provide a name!";
        exit; //This may not be what you want to do here, it's an example action
}

if(isset($_POST['LastName']))
{
        $name = $_POST['LastName'];
}
else
{
    echo "You must provide a last name!";
        exit; //This may not be what you want to do here, it's an example action
}

if(isset($_POST['Phone']))
{
        $name = $_POST['Phone'];
}
else
{
    echo "You must provide a phone number!";
        exit; //This may not be what you want to do here, it's an example action
}


//Set up the query using anonymous values
$sql="INSERT INTO people (Name, LastName, Phone) VALUES ('?','?','?')";
$sth = $DB->prepare($sql);

try
{
        //Attempt to execute the insert statement
        $sth->execute(array($_POST[Name], $_POST[LastName], $_POST[Phone]));
        echo "Record Added";

}
catch(PDOException $e)
{
        //If the insert failed, then you can handle the error, and determine
        //what further steps need to be taken.
        echo "Record Not Added";
}

Here’s another question with a similar setting, that may also be useful to you:

https://stackoverflow.com/a/10414922/1507210

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement