Reputation: 17
Via a form on the site, organizations can be added to the database. The organization ID is unique in PhpMyAdmin, but organizations with the same name can be added multiple times. Any suggestions on how to fix this within PHP or PhpMyAdmin?
The database has the following structure:
And in funtions.php, I have the following code:
// 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>";
}
}
And for reference, this is the HTML code:
<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>
Upvotes: 1
Views: 354
Reputation: 547
Basically you need to add unique index to the organizations table but you have to consider proper error handling since any attempt to add organization with duplicated name will throw an error.
ALTER TABLE `organizations` ADD UNIQUE INDEX `unq_organization` (`organization`);
Upvotes: 2