Christophe Harris Christophe Harris - 22 days ago 6
MySQL Question

Can anyone tell me why this row is being inserted twice into my database?

When I click my 'Create' button I want the record to be added to my category table, however for some reason it is being added twice - even though I just click the button once. Any ideas why that may be? I can't see where else the

if (isset($_POST['create'])) {
could be called from. I only have 4 pages in my whole project.

<?php require('dbConnect.php');

//use the variables we created in volleyLogin.php
$username = $_SESSION['username'];
$user_id = $_SESSION['user_id'];
echo "user name is " . $username . "<br>";
echo "user id is " . $user_id . "<br>";

if (isset($_POST['create'])) {

$category = ($_POST['category']);
$name = ($_POST['name']);
$phonenumber = ($_POST['phonenumber']);
$address = ($_POST['address']);
$comment = ($_POST['comment']);

//check if the category being entered is already there
$check="SELECT COUNT(*) FROM category WHERE cat_name = '$_POST[category]'";
$get_value = mysqli_query($con,$check);
//check the number of values of the category being posted
$data = mysqli_fetch_array($get_value, MYSQLI_NUM);
//if the category name already exists in the category table
if($data[0] >= 1) {
echo "This Already Exists<br/>";

else if ($data[0] < 1)
//if it's not in there, then add the category in the category table.

$sql = "INSERT INTO category VALUES(NULL, '{$category}', '$user_id')";
$rs1=mysqli_query($con, $sql);

if ($con->query($sql) === TRUE) {
echo "Yes, it's been added correctly";

} else {
echo "Error: " . $sql . "<br>" . $con->error;



<!doctype html>
<h2>Create new Contact</h2>
<form method="post" action="" name="frmAdd">
<p><input type="text" name = "category" id = "category" placeholder = "category"></p>
<p><input type="text" name = "name" id = "name" placeholder = "name"></p>
<p><input type="text" name = "phonenumber" id = "phonenumber" placeholder = "phone number"></p>
<p><input type="text" name = "address" id = "address" placeholder = "address"></p>
<p><input type="text" name = "comment" id = "comment" placeholder = "comment"></p>

<p><input type="submit" name = "create" id = "create" value = "Create new Contact"></p>
<a href="exit.php">Exit</a>




You're running the $sql query twice, with two different methods:

$rs1=mysqli_query($con, $sql); 

        if ($con->query($sql) === TRUE) {

That's why you're getting duplicate entries.

You should either remove $rs1 as it's not being used, or verify it's value on the conditional instead of running the function again.