Jump to content

check if unique field exits or not


rafal

Recommended Posts

Hello everybody,

i try to check if the unique field inventar exists or not before i insert new record.

if the inventar exits the user should get error message.

but i dont know how to do this.

 

thank you very much for your help.

Rafal

 

here is my code

<?php
include("123.php");
$inventar = $link1->real_escape_string($_POST["inp_inventar"]);
$product = $link1->real_escape_string($_POST["inp_product"]);
$price = $link1->real_escape_string($_POST["inp_price"]);

$link1 = new mysqli("$hoster", "$nameuser", "$password", "$basedata") or die ("Connection Error!"); error_reporting (0);
$check_inventar = mysqli_query($link1, "SELECT inventar FROM products WHERE inventar='$inventar'");
$check_inventar_num = mysqli_num_rows($check_inventar);
if (isset($_POST['inp_submit']) AND $check_inventar_num = 0)
{
$query1 = "INSERT INTO products
(inventar, product, price)
VALUES ('$inventar', '$product', '$price')";
$result1 = $link1->query($query1) or die("Database Error!");
if ($result1 == true)
{
header ( 'Location:insert.php' );
}
}
else { echo "there is already product with same inventar id!"; }
mysqli_close($link1);
?>
Link to comment
https://forums.phpfreaks.com/topic/292638-check-if-unique-field-exits-or-not/
Share on other sites

Create a unique index on (product, inventor).

 

This will then give a duplicate key error if you attempt to add the same combination

 

Alternatively, having set up that index, change your query to

INSERT INTO products
(inventar, product, price)
VALUES ('$inventar', '$product', '$price')
ON DUPLICATE KEY UPDATE price = $price

which will update the existing record instead of trying to insert a duplicate

Thanks Barand, i made already inventor as unique key in the mysql database.

i dont want want update the price or product.

i want make insert of duplicate inventor not possible.

the user should get the following error message "there is already product with same inventor id!".

 

thanks again

Rafal

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.