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
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

Edited by Barand
Link to comment
Share on other sites

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

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.