在PHP中插入重复记录的限制

时间:2020-04-22 04:53:50

标签: php validation duplicates

我是PHP的新手,我已经编写了PHP代码,并在Internet上进行了一些探索,在Mysql表中插入了一条记录,在将重复功能添加到代码中之前,它可以正常工作。但是现在我对重复记录添加了限制后陷入困境。我已经尝试过了,但是在提交后我失去了代码的响应,现在没有任何消息。我希望插入一个基于条件的重复记录限制,并在重复时获取消息。欢迎对此事提供专家指导。

创建(产品):代码

<?php
// include database and object files
include_once 'config/database.php';
include_once 'objects/product.php';
include_once 'objects/category.php';

// get database connection
$database = new Database();
$db = $database->getConnection();

// pass connection to objects
$product = new Product($db);
$category = new Category($db);

// set page headers
$page_title = "Create Product";
include_once "layout_header.php";
?>

<!-- PHP post code starts here -->
<?php 
// if the form was submitted
if($_POST){ 
    // set product property values
    $product->name = $_POST['name'];
    $product->price = $_POST['price'];
    $product->description = $_POST['description'];
    $product->category_id = $_POST['category_id'];
    $image=!empty($_FILES["image"]["name"])
            ? sha1_file($_FILES['image']['tmp_name']) . "-" . basename($_FILES["image"]["name"]) : "";
    $product->image = $image; 

    // Duplicate Validation
    if($product->duplicate()){
        echo "<div class='alert alert-danger'>Already entered product.</div>";
exit;
    }

    // create the product
    if($product->create()){
        echo "<div class='alert alert-success'>Product was created.</div>";
        // try to upload the submitted file, uploadPhoto() method will return an error message, if any.
        echo $product->uploadPhoto();
    }

    // if unable to create the product, message here
    else{
        echo "<div class='alert alert-danger'>Unable to create product.</div>";
    }
}
?>

对象(产品):代码

<?php
class Product{

    // database connection and table name
    private $conn;
    private $table_name = "products";

    // object properties
    public $id;
    public $name;
    public $price;
    public $description;
    public $category_id;
    public $image;
    public $timestamp;

    public function __construct($db){
        $this->conn = $db;
    }

    function duplicate(){
        $query = "SELECT * FROM " . $this->table_name . " WHERE name=? AND category_id=? LIMIT 1";
        $stmt = $this->conn->prepare($query);
        $stmt->bind_param('si', $name, $category_id);
        $stmt->execute();
        $result = $stmt->get_result();
        $nameCount = $result->num_rows;
        $stmt->close();

        if($nameCount > 0){
            return true;
        }
        return false;
    }

0 个答案:

没有答案