Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
232 views
in Technique[技术] by (71.8m points)

mysql - How to use SUBSTRING and use it on making a data unique in PHP

I am trying to do this in my PHP code, the thing is I haven't figured it out yet. I want to make the first 3 characters UNIQUE but still the data is saved. For example if I input GTX-1070 and will Input another entry named GTX-3080 it should not be saved because "GTX" was already been used. I am doing this without using unique constraint in SQL.

Here is my PHP code

<?php

include('../include/connect.php');

   $control_no = "";

    if($_SERVER["REQUEST_METHOD"]=="POST")
        {
      
        $control_no = $_REQUEST['control_num'];

        
        if(isset($_POST['subBtn']))
        {
        $control_no = mysql_real_escape_string($_POST["control_num"]);
        $con->next_result();
        $control_check_res = mysqli_query($con, "SELECT SUBSTRING(control_no, 1, 3) FROM tools_masterlist WHERE control_no = '$control_no'");
        
        if (mysqli_num_rows($control_check_res)) 
        {
            echo '<script> $("#control_num_Modal").modal("show"); </script>';
        }

        else 
        {

            $query = "INSERT INTO tools_masterlist (control_no)
            VALUES ('$control_no')";
            $con->next_result();
            $result=mysqli_query($con,$query);
           
            if(!$result)
            {
                echo '<script> $("#control_num_Modal").modal("show"); </script>';
            }
            else
            {
                echo '<script> $("#maModal").modal("show"); </script>';
            }
         

        }

        }

    }

?>

I have editted my code because I want to highlight the part where I coded my SUBSTRING query and the condition. I am really confused right now on what should I put in my condition thank you very much in advance for the help.

question from:https://stackoverflow.com/questions/65558256/how-to-use-substring-and-use-it-on-making-a-data-unique-in-php

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

In your database, the column for "GTX" or that 3 unique character you are pertaining to, must be set in PRIMARY KEY so all data that is to be inserted is unique.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...