mysqlli_query中的连接变量未定义

时间:2015-05-05 23:34:21

标签: php mysql sql mysqli undefined

我遇到以下问题:$con未定义,尽管我使用它来连接数据库。我不明白为什么会这样。

<?php
    define("DB_HOST", "localhost");
    define("DB_NAME", "Bar_buddy_users");
    define("DB_USER", "local_server");
    define("DB_PASSWORD","010203");
    error_reporting( E_ALL );
    ini_set('display_errors', 1);
    $con = new mysqli(DB_HOST,DB_USER,"010203",DB_NAME) or die("Failed to connect to database");
    if ($con->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    }
    echo "Connected successfully";
    function NewUser(){
        $first_name= $_POST["firstname"];
        $last_name = $_POST["lastname"];
        $email = $_POST["email"];
        $password = $_POST["password"];
        $query = "INSERT INTO Users (firstname, lastname, email, password) VALUES ('$first_name', '$last_name', '$email', '$password')";
        mysqli_query($con,$query);
        mysqli_close($con);
    }
?>

1 个答案:

答案 0 :(得分:1)

$con作为参数传递给您的函数。

mysqli_close($con);移到函数外的某处。关闭连接后,它将再次无效。所以你必须在没有关闭的情况下使用同一个,或者每次都创建一个新的。

function NewUser($con){

        $first_name= $_POST["firstname"];
        $last_name = $_POST["lastname"];
        $email = $_POST["email"];
        $password = $_POST["password"];

        $query = "INSERT INTO Users (firstname, lastname, email, password) VALUES ('$first_name', '$last_name', '$email', '$password')";
        mysqli_query($con,$query);
    }
...

        mysqli_close($con);