-1

this code is used to check slug or any value that is already existed in database or not while performing insert operation.

<?php
    if($_SERVER['REQUEST_METHOD'] === 'POST') {
        $slug =$_POST['slug'];
        $title =$_POST['title'];
        $description= $_POST['description'];
        //$created_date=$_POST['created_date'];
        // $updated_date = $_POST['updated_date'];
        $status = $_POST['status'];
        $sql = "INSERT INTO Pages SET slug='$slug', title='$title', description='$description', status='$status'"; // query to insert into database


        $result = $con->query($sql);
        if ($result->num_rows > 0) { //checking the db table*emphasized text*
            $data = $result->fetch_assoc($);
            echo "Slug already used"; //duplicate slug is existed.
            die;
        }
        else {
            echo "No slug used"; //when no similar slug is used
            die;
        }
        header("Location: pages.php?success=Record added successfully.");
        die;
    }
?>
Sandeep
  • 29
  • 2
  • 1
    Use `select` queary in your project check duplicate entry – A.A Noman Feb 25 '18 at 09:33
  • Possible duplicate of [How to Check if value exists in a MySQL database](https://stackoverflow.com/questions/11292468/how-to-check-if-value-exists-in-a-mysql-database) – Progman Feb 25 '18 at 17:07

1 Answers1

0

the following code check where there is slug has been used or not. If used it redirects to the edit page other wise it redirects to the listing page.

if($_SERVER['REQUEST_METHOD'] === 'POST'){
  $slug =$_POST['slug'];
  $title =$_POST['title'];
  $description= $_POST['description'];
    $status = $_POST['status'];

  $sql = "SELECT * from Pages where slug='$slug'";
  $resultDuplicate = $con->query($sql);
  if($resultDuplicate->num_rows > 0) {
    header("Location: pages_add.php?error=Slug already exists, choose new.");
    die;
  }
  else {
    $sql = "INSERT INTO Pages SET slug='$slug', title='$title', description='$description', status='$status'";
    $con->query($sql);
   header("Location: pages.php?success=New page added successfully.");
    die; 
  }
}
Sandeep
  • 29
  • 2