phpmyadmin 通过PHP提交表单时,如何防止SQL数据库中的重复名称?

brqmpdu1  于 2022-11-09  发布在  PHP
关注(0)|答案(1)|浏览(124)

通过网站上的表单,可以将组织添加到数据库中。组织ID在PhpMyAdmin中是唯一的,但是具有相同名称的组织可以被多次添加。关于如何在PHP或PhpMyAdmin中解决这个问题,有什么建议吗?
数据库具有以下结构:
SQL table
在functions.php中,我有以下代码:

// Add sport organizations to database
if (isset($_POST['button'])){
    $data = array(
        'organization' => $_POST['organization'],
        'description' => $_POST['description'],
        'website' => $_POST['website'],
        'facebook' => $_POST['facebook'],
        'instagram' => $_POST['instagram'],
        'phone' => $_POST['phone'],
        'email' => $_POST['email'],
    );
    $table_name = 'organizations';

    $result = $wpdb->insert($table_name, $data, $format=NULL);

    if ($result==1) {
        echo "<script>alert('Organizations saved');</script>";
    }
    else {
        header("refresh: 0; url=/");
        echo "<script>alert('Unable to save organization');</script>";
    }
}

下面是HTML代码,供您参考:

<form autocomplete="off" role="form" method="POST">
            <div class="container">
                <div class="form-group">
                    <input id="organization" name="organization" type="text" placeholder="Name of organization" class="form-control input-sm" required="">
                </div>
                <div class="form-group">
                    <input id="description" name="description" type="textarea" placeholder="Description" class="form-control input-sm" required="">
                </div>
                <div class="form-group">
                    <input id="website" name="website" type="text" placeholder="Website" class="form-control input-sm">
                </div>
                <div class="form-group">
                    <input id="facebook" name="facebook" type="text" placeholder="Facebook" class="form-control input-sm">
                </div>
                <div class="form-group">
                    <input id="instagram" name="instagram" type="text" placeholder="Instagram" class="form-control input-sm">
                </div>
                <div class="form-group">
                    <input id="phone" name="phone" type="text" placeholder="Phone" class="form-control input-sm">
                </div>
                <div class="form-group">
                    <input id="email" name="email" type="text" placeholder="Email" class="form-control input-sm">
                </div>
            </div>
<div class="container">
                <div class="row justify-content-center">
                    <div class="col-xs-4 col-sm-4 col-md-4">
                        <input type="submit" class="btn btn-info btn-block" name="submitbtn">
                    </div>
                </div>
            </div>
        </form>
qni6mghb

qni6mghb1#

基本上,您需要将唯一索引添加到组织表中,但您必须考虑正确的错误处理,因为任何尝试添加具有重复名称的组织的操作都将引发错误。

ALTER TABLE `organizations` ADD UNIQUE INDEX `unq_organization` (`organization`);

相关问题