检查数据是否已存在于MySQL中

时间:2016-02-18 04:27:27

标签: php mysql post

我正在尝试检查数据状况。如果数据已存在,则不会插入。否则会插入。但问题是数据仍然插入,尽管它已经存在!

<?php 
    if($_SERVER['REQUEST_METHOD']=='POST'){

        //Getting values
        $project = strtoupper($_POST['project']);
        if($project != null)
        {
            //Importing our db connection script
            require_once('dbConnect.php');
            $sql="SELECT * FROM Project WHERE project='$project'";
            $check=mysqli_fetch_array(mysqli_query($con,sql));
            if(isset($check))
            {
                // no need insert
            }
            else{
                //Creating an sql query
        $sql = "INSERT INTO Project(project) VALUES ('$project')";
            }
        //Executing query to database
        if(mysqli_query($con,$sql)){
            echo ' Added Successfully';
        }else{
            echo 'Could Not Add Project';
        }
        }
        else
        {
        echo "data is null";
        }
        //Closing the database 
        mysqli_close($con);
    }
?>

3 个答案:

答案 0 :(得分:3)

您的代码中存在多个问题。我将首先回答你的问题。永远不会设置$check,因为您的查询未被执行。 $中缺少$sql。此外,始终需要在查询中使用之前清理/转义用户输入。如果你没有对它进行消毒,那么黑客可能会在你的查询中注入不需要的代码,做一些你不想做的事情。请参阅下面的更新和优化代码:

<?php 
if($_SERVER['REQUEST_METHOD']=='POST'){
    //Getting values
    if(isset($_POST['project']) && !empty($_POST['project'])){
        //Importing our db connection script
        require_once('dbConnect.php');
        $project = strtoupper($_POST['project']);
        //Security: input must be sanitized to prevent sql injection
        $sanitized_project = mysqli_real_escape_string($con, $project);
        $sql = 'SELECT * FROM Project WHERE project=' . $sanitized_project . ' LIMIT 1';// LIMIT 1 prevents sql from grabbing unneeded records
        $result = mysqli_query($con, $sql);
        if(mysqli_num_rows($result) > 0){
            // a match was found
            // no need insert
        }
        else{
            //Creating an sql query
            $sql = "INSERT INTO Project(project) VALUES ('$sanitized_project')";
            //Executing query to database
            if(mysqli_query($con,$sql)){
            echo('Added Successfully');
        }
        else{
            echo('Could Not Add Project');
        }
    }
    else{
        echo('data is null');
    }
    //Closing the database 
    mysqli_close($con);
}
?>

答案 1 :(得分:2)

纠正这一行$check=mysqli_fetch_array(mysqli_query($con,sql));,在$之前错过了sql。这就是条件评估为假的原因。

答案 2 :(得分:1)

执行sql应该放入“需要插入”,否则{}。