Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/238.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/60.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 如果数据库中存在值,如何验证该值?_Php_Mysql_Mysqli - Fatal编程技术网

Php 如果数据库中存在值,如何验证该值?

Php 如果数据库中存在值,如何验证该值?,php,mysql,mysqli,Php,Mysql,Mysqli,我想首先检查数据是否已经在数据库中。这是我的代码: <?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_

我想首先检查数据是否已经在数据库中。这是我的代码:

<?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';
            }
    }

?>

在此代码中,它始终运行已存在的
课程名称
,即使它未保存在
数据库中
。有人能帮我吗?提前感谢您

MySQL的
count(…)
函数将始终返回一个值,因此当您使用
mysqli_num_rows
时,它将始终是
>0
(查询返回带有count()值的行-该值可以是
0
或更多…)

您应该检查
计数(…)
的值,以查看其
>0

更改此项:

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


现在它总是运行
$query\u update
即使值已经存储在数据库中,您确定值真的存储在数据库中吗?在我的页面中,在您提交表单后,表中的所有值都已被提取不确定我是否理解您的答复。
对不起,我在我的页面上看到了这个消息
$fetch = mysqli_fetch_array($stmt);
if ($fetch[0] > 0) {
    echo "Course Name Already Exist";
}