I have a page where the user want to add new category to the database,
I want to check if the category is already added before in the database or not,if it is new one add it to the database, it is working fine but it adds it many times(equal to the data in the table) i know it is because of foreach
,how can it be done?and also how to alert to the user that it is already exists?
Php code:
<?php
include_once "connect.php";
$stmt ="SELECT distinct Category_Name FROM Categories";
foreach ($conn->query($stmt) as $row)
{
if ($row['Category_Name'] != $_POST["CatName"])
{
$sql ="INSERT INTO Categories (Category_Name) VALUES (:CatName)";
$result=$conn->prepare($sql);
$result->bindparam(':CatName', $_POST["CatName"], PDO::PARAM_INT);
$result->execute();
}
else
{
return false;
}
}
?>
Javascript Code:
function AddNewCategory()
{
var CatName=document.getElementById("CatNametxt").value;
$.ajax({
type:"POST",
url:"add_category.php",
data:'CatName=' + CatName,
success: function(data)
{
alert("Category Added Successfully!");
}
})
}
Edit1 I changed it to the following and it worked fine,but how to alert to the user that this category is inserted before?
$stmt ="SELECT * FROM Categories WHERE Category_Name='".$_POST["CatName"]."'";
$queryresult = $conn->query($stmt)->fetchAll(PDO::FETCH_ASSOC);
if (count($queryresult) == 0)
{
$sql ="INSERT INTO Categories (Category_Name) VALUES (:CatName)";
$result=$conn->prepare($sql);
$result->bindparam(':CatName', $_POST["CatName"], PDO::PARAM_INT);
$result->execute();
}