peace_love
peace_love

Reputation: 6471

How can I check if a value already exists in mySQL database?

I want to store a name in the mySQL database. When I click the submit button, PHP should check if the name already exists in the database. If yes then do not submit and print an error message:

Name already exists in database.

<?php 
    if ( !empty($_POST)) {

            $name = $_POST['name'];

            $valid = true;

            if ($valid) {
                $pdo = Database::connect();
                $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
                $sql = "INSERT INTO people (name) values(?) ";
                $q = $pdo->prepare($sql);
                $q->execute(array($name));

            }
        }
    ?>

    <form action="form.php" method="post">
          <input name="name" type="text"  value="<?php echo !empty($name)?$name:'';?>">
          <button type="submit" >Submit</button>                
    </form>

Upvotes: 1

Views: 1968

Answers (2)

Mohamed abd almohsin
Mohamed abd almohsin

Reputation: 11

you could declare the column as unique and check if the query executes or not, for example:

$query = $pdo->prepare("SELECT name FROM table WHERE name = :name");
$query->bindValue(':name', '$name');
if ($query->execute()){
    //no duplicate
}
 else {
    //error, check the error code.
    echo "$stmt->errorCode()";
}

$query-> execute will retun true on success and false other wise, and the database will return an error when the input is a duplicate in a unique coulmn. I think Making the duplication check in the database is safer.

Upvotes: 0

Shehary
Shehary

Reputation: 9992

Try following query to check if a value already exists in mySQL database?

$q = $pdo->prepare("SELECT name FROM people WHERE name = :name LIMIT 1");
$q->bindValue(':name', '$name');
$q->execute();

if ($q->rowCount() > 0){
    $check = $q->fetch(PDO::FETCH_ASSOC);
    $row = $check['name'];
    // Do Something If name Already Exist
} else {
    // Do Something If name Doesn't Exist
}

Upvotes: 4

Related Questions