SNos SNos - 11 months ago 94
MySQL Question

PHP - mysqli - check the table if a value is already inserted

I Am trying to check if the REF number added when creating a new

mysql
row is already in use. I don't have problems in adding a new row however, the script does not check the database first.

if ($_POST['add_new_bus']){
if (($_POST['add_ref'] != "")&&($_POST['add_name'] != "")&&($_POST['add_address'] != "")&&($_POST['add_area'] != "")){
$add_ref = $_POST['add_ref'];
$add_name = $_POST['add_name'];
$add_address = $_POST['add_address'];
$add_area = $_POST['add_area'];
$chech_sql = "INSERT INTO `Details` (`REF`) VALUES ('$add_ref')";
if (!($conn->query($chech_sql))) {
echo "REF is already in use";
}else{
mysqli_query($conn, "INSERT INTO `Details` (`REF`, `NAME`, `ADDRESS`, `AREA`) VALUES ('$add_ref', '$add_name', '$add_address', '$add_area')");
echo "<p style='float:right;'>" . $_POST['add_name'] . " " . "has been added to the register with REF number:" . " " . $_POST['add_ref'] . "</p>";
}
}


Any Idea how to check if the REF number is already in use?

Answer Source

For giving you a correct idea how to do it, Please check below code:-

<?php
if (isset($_POST['add_new_bus']){
    if (($_POST['add_ref'] != "") &&($_POST['add_name'] != "")&&($_POST['add_address'] != "")&&($_POST['add_area'] != "")){
        $add_ref = $_POST['add_ref'];
        $add_name = $_POST['add_name'];
        $add_address = $_POST['add_address'];
        $add_area = $_POST['add_area'];
        $chech_sql = "SELECT add_ref FROM Details WHERE add_ref = '".$add_ref."'";
        $result = $conn->query($chech_sql);
   if (mysqli_num_rows($result) > 0) {
        echo "REF is already in use";
    }else{
        mysqli_query($conn, "INSERT INTO `Details` (`REF`, `NAME`, `ADDRESS`, `AREA`) VALUES ('$add_ref', '$add_name', '$add_address', '$add_area')");
        echo "<p style='float:right;'>" . $_POST['add_name'] . " " . "has been added to the register with REF number:" . " " . $_POST['add_ref'] . "</p>";
        }
    }
}
?>

Note:- checking variables value and other things is up to you. because you only have them in your code.thanks.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download