php - How can I check if a value already exists in mySQL database? -
i want store name
in mysql database. when click submit button, php should check if name
exists in database. if yes not submit , print error message:
name 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 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>
try following query check if value exists in mysql database?
$q = $pdo->prepare("select name people name = :name limit 1"); $q->bindvalue(':name', '$name'); $q->execute(); if ($q->rowcount() > 0){ $check = $q->fetch(pdo::fetch_assoc); $row = $check['name']; // if name exist } else { // if name doesn't exist }
Comments
Post a Comment