注意:未定义的变量:插入时

时间:2017-02-22 16:24:23

标签: php mysql

我是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

我试图google但到目前为止无济于事。有人有什么想法吗?

错误指向第76行

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

2 个答案:

答案 0 :(得分:0)

这是帮助mysql连接的a link

$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'");

希望有所帮助

答案 1 :(得分:0)

我刚刚&lt;从代码的最开始就缺少

?php include(“config.php”);?&gt;

而不是

 

其中一个就在那里,但却看不到它的缺失。一定是因为意外或某事而被删除而没有注意到。