说明:
逻辑是对数据进行判断,在传过来的数据为空、或者数据库已有一样的数据的情况下,不插入。
那么将这两种情况下的array下面的key赋值,同样对其他数据进行判断,只有所有数据都满足的情况下,才执行插入数据库的操作。
知识点:mysqli_num_rows
mysql_num_rows是PHP语言的中的函数,其表示取得结果集中行的数目。此命令只对SELECT语句有效。要取得被 INSERT,UPDATE 或者 DELETE 查询所影响到的行的数目,用 mysql_affected_rows()。
成果展示:
第一步:建立数据库
第二步、书写代码
<?php error_reporting(0); $con = mysqli_connect("localhost","root","","avoid_duplicaton"); if(isset($_POST['insert'])) { # code $uname = $_POST['uname']; $email = $_POST['email']; $pass = $_POST['pass']; $errors =array(); $u = "SELECT username FROM new where username='$uname'"; $uu = mysqli_query($con,$u); $e = "SELECT email FROM new where email='$email'"; $ee = mysqli_query($con,$e); if(empty($uname)){ $errors['u'] = "Username Requirs"; }else if (mysqli_num_rows($uu) > 0) { # code... $errors['u'] = "Username Exist"; } if(empty($email)){ $errors['e'] = "Email Requirs"; }else if (mysqli_num_rows($ee) > 0) { # code... $errors['e'] = "Email Exist"; } if(empty($pass)){ $errors['p'] = "Password Requirs"; } echo count($errors); if (count($errors)==0) { # code... $query="INSERT INTO new(username,email,password) VALUES('$uname','$email','$pass')"; $result =mysqli_query($con,$query); if ($result) { # code... echo "<script>alert('done')</script>"; } }else{ echo "<script>alert('failed')</script>"; } } ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <!-- <link href="stylesheet" type="text/css" href="https://cdn.usebootstrap.com/bootstrap/4.4.1/css/bootstrap.min.css"> --> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-KK94CHFLLe+nY2dmCWGMq91rCGa5gtU4mk92HdvYe+M/SXH301p5ILy+dN9+nJOZ" crossorigin="anonymous"> <title>Document</title> </head> <body> <div class="container-fluid"> <div class="col-md-12"> <div class="row"> <div class="col-md-3"></div> <div class="col-md-6 jumbotron bg-info"> <form method="post"> <div class="form-group"> <label>Username</label> <input type="text" name="uname" placeholder="Enter username" class="form-control" autocomplete="off"> <p class="text-daner"><?php if (isset($errors['u'])) echo $errors['u']; ?></p> </div> <div class="form-group"> <label>Email</label> <input type="text" name="email" placeholder="Enter email" class="form-control" autocomplete="off"> <p class="text-daner"><?php if (isset($errors['e'])) echo $errors['e']; ?></p> </div> <div class="form-group"> <label>Password</label> <input type="text" name="pass" placeholder="Enter pasowrd" class="form-control" autocomplete="off"> <p class="text-daner"><?php if (isset($errors['p'])) echo $errors['p']; ?></p> </div> <input type="submit" name="insert" value="insert" class="btn btn-success"> </form> </div> </div> </div> </div> </body> </html>
参考:https://www.youtube.com/watch?v=c4DVJJZ7p64