我刚接触PHP并遇到问题。我正在尝试检查表中是否存在ID,如果不存在,则插入记录,但遇到麻烦。我目前有:

            <?php

            if(isset($_POST['add'])){
            $id              = $_POST['id'];
            $first_name      = $_POST['first_name'];
            $last_name       = $_POST['last_name'];
            $dob             = $_POST['dob'];
            $telephone       = $_POST['telephone'];
            $job_title       = $_POST['job_title'];
            $site            = $_POST['site'];
            $department      = $_POST['department'];
            $email           = $_POST['email'];
            $pass1           = $_POST['pass1'];
            $pass2           = $_POST['pass2'];


            $cek = mysqli_query($db, "SELECT * FROM employees WHERE id='$id'");
            if(mysqli_num_rows($cek) == 0){

                if($pass1 == $pass2){
                    $pass = md5($pass1);
                    $insert = mysqli_query($db, "INSERT INTO employees (id, first_name, last_name, dob, telephone, job_title, site, department, email, password)
                                                        VALUES('$id','$first_name', '$last_name', '$dob', '$telephone', '$job_title', '$site', '$department', '$email', '$pass')") or die('Error: ' . mysqli_error($db));
                    if($insert){
                        echo '<div class="alert alert-success alert-dismissable"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>Employee added</div>';
                    }else{
                        echo '<div class="alert alert-danger alert-dismissable"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>Ups, Error, user not added</div>';
                    }
                } else{
                    echo '<div class="alert alert-danger alert-dismissable"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>Passwords do not match</div>';
                }
            }else{
                echo '<div class="alert alert-danger alert-dismissable"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>Employee Id Exists</div>';
            }
        }
        ?>


我遇到错误:注意:未定义的变量:db

我已经尝试谷歌,但无济于事。有人有想法么?

错误指向第76行,即

        $cek = mysqli_query($db, "SELECT * FROM employees WHERE id='$id'");

最佳答案

这是a link以帮助与mysql连接

$db=mysqli_connect("localhost","my_user","my_password","my_db");
// Check connection
if (mysqli_connect_errno())
{
    echo "Failed to connect to MySQL: " . mysqli_connect_error();
}


那么你可以使用

 $cek = mysqli_query($db, "SELECT * FROM employees WHERE id='$id'");


希望能有所帮助

10-07 17:48