PHP: Ignoring whitespaces and casing in form validation

64 Views Asked by At

I'm creating an educational platform in which courses (course codes) are created. I want to be able to prevent a new course code from being inserted ignoring the case being used or use of whitespace. e.g if "PHY 101" already exists and one types in "phy101". It should reject the new entry.

$new_course = $_POST['new_course'];
$sql = mysqli_query($conn, "SELECT * FROM courses WHERE course = '$new_course'") or die(mysqli_error($conn));
        $num_row=mysqli_num_rows($sql);
        if($num_row === 1){
          echo "<script>
          alert('Course code already exists.');
          window.location = 'create_newcourse.php';
          </script>";                                
        }
1

There are 1 best solutions below

3
mitkosoft On BEST ANSWER

If you already have records on your courses table, then you need to equalize both strings (course column and $_POST['new_course']) upfront:

$new_course = strtolower(str_replace(' ', '',$_POST['new_course']));
$sql = mysqli_query($conn, "SELECT * FROM courses WHERE LOWER(REPLACE(`cource`, ' ', '')) = '$new_course'") or die(mysqli_error($conn));

If you don't need formatted $new_course value further, you can perform both modifications only on SQL level, like:

$sql = mysqli_query($conn, "SELECT * FROM courses WHERE LOWER(REPLACE(`cource`, ' ', '')) = LOWER(REPLACE('$new_course', ' ', ''))") or die(mysqli_error($conn));