我遇到以下问题:$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);
}
?>
答案 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);