marilee arconada marilee arconada - 2 months ago 8
MySQL Question

How to validate the value if it exist in the database?

I want first to check if the data is already in the database or not. So here is my code:

<?php

include '../session.php';
require_once 'config.php';

$tc_course_name2 = strtoupper($_POST['tc_course_name']);
$tc_course_code2 = strtoupper($_POST['tc_course_code']);

$query = "SELECT COUNT(tc_course_name) FROM tc_courses WHERE tc_course_name = '{$tc_course_name2}'";
$stmt = mysqli_query($conn, $query);
$fetch = mysqli_num_rows($stmt);

if ($fetch > 0) {

echo "Course Name Already Exist";
}

else {
$query_update = "INSERT INTO tc_courses (tc_course_code,tc_course_name) VALUES('$tc_course_code2','$tc_course_name2')";
if (mysqli_query($conn,$query_update)) {
header("Location: ../admin/add_new_training_course.php");
}
else {
echo 'Something went wrong';
}
}

?>


In this code, it always run the
Course Name Already Exist
even it is not saved on the
database
. Can someone help me here? Thank you in advance

Answer

MySQL's count(...) function will always return a value, so when you use mysqli_num_rows it will always be > 0 (the query returns row with the count() value - that value can be 0 or more...).

You should check the value of the count(...) to see if its >0

change this:

$fetch = mysqli_num_rows($stmt);
if ($fetch > 0) {
    echo "Course Name Already Exist";
}

to

$fetch = mysqli_fetch_array($stmt);
if ($fetch[0] > 0) {
    echo "Course Name Already Exist";
}