I want my form field to return an error if it's already in the database

25 Views Asked by At

Currently I have connected the form to the database. The form registration field is only supposed to submit numbers to the database. Now number I put into the form before can still show multiple times on the database.

if a number is in the database, it should throw an error that number already exist.

This is the html code:

<?php
    session_start();
    ?>
    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    </head>
    <body>

    <div class="container">
    <div class="row">
    <div class="col-md-6 offset-md-3">
    <div class="form-container">
    <h2>Register</h2>
    <form action="connect.php" method="post">
    <div class="form-group">
    <input type="tel" name="phone" placeholder="Enter your phone number" required>
    </div>
    <div class="form-group">
    <input type="submit" value="Register">
    </div>
    </form>
    <?php
    if(isset($_SESSION['status']))
    {
    ?>
    <div class="alert alert-warning alert-dismissible fade show" role="alert">
    <strong>Hey !</strong> <?= $_SESSION['status']; ?>
    <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
    </div>
    <?php 
    unset($_SESSION['status']);
    }
    ?>
    </div>
    </div>
    </div>
    </div>

    </body>
    </html>

Then this is the PHP code

<?php
    session_start();
    $phone = $_POST['phone'];

    // Database connection
    $conn = new mysqli('localhost','solflare_spynew','Workouts.com','solflare_spynew');
    if($conn->connect_error){
    echo "$conn->connect_error";
    die("Connection Failed : ". $conn->connect_error);
    } else {
    $stmt = $conn->prepare("insert into spywanuser(phone) values(?)");
    $stmt->bind_param("i",$phone);
    $execval = $stmt->execute();
    $stmt->store_result();
    $rnum = $stmt->num_rows;
    if ($rnum==0) {
    $stmt->close();
    echo $execval;
    echo "Registration successful...";
    $stmt->close();
    $conn->close();
    } 
    }
    
    //after insert or update 
    $_SESSION['status'] = "Welcome. Login";
    
    header("Location: register.php");
    ?>
0

There are 0 best solutions below