包含在另一个文件中时,连接变量为null! [英] Connection variable null when including in another file!
问题描述
大家好,我是一名PHP新手,但对其他编程语言有一定的经验。我试图使用不同文件中定义的连接设置将简单值输入数据库:
//DBConnect.php
Hello everyone, i am a PHP newbie but have some experience with other programming languages. I am trying to enter simple values into the database using the connection settings defined in a different file:
//DBConnect.php
$serverName="localhost";
$userName="root";
$passWord="";
$db="inventorymgmtdb";
$conn=mysqli_connect($serverName,$userName,$passWord,$db);
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
exit();
}
我已将此文件包含在我的entercategory.php文件中:
I have included this file in my entercategory.php file:
<?php
include("DBConnect.php");
function insertCategory($categoryName,$categoryDescription)
{
global $conn;
$insertQuery="insert into tbl_categories(CategoryName,CategoryDescription) values('$categoryName','$categoryDescription')";
$retVal=mysqli_query($conn,$insertQuery);
if(!$retVal)
die('Error entering to database'.mysqli_error($conn));
echo "Entered Successfully!";
mysqli_close($conn);
}
?>
现在,系统抱怨$ conn为null(mysqli_query()期望参数1为mysqli,给出null ...)。
我在这里做错了什么?有人可以解释一下吗?
编辑:该函数调用如下:
Now, the system is complaining that the $conn is null ("mysqli_query() expects parameter 1 to be mysqli,null is given...").
What am i doing wrong here? Can someone please explain?
The function is called as follows:
if(isset($_POST["btnCreateCategory"]))
{
insertCategory($_POST["txtCategoryName"],$_POST["txtCategoryDescription"]);
}
编辑:
我将DBConnect.php的代码直接放在entercategory.php中。 $ conn变量不为null并且工作得很好。但是,我无法理解为什么当代码放在单独的文件(DBConnect.php)中时,$ conn变量变为null。有人可以帮忙吗?
I have put the code of DBConnect.php directly in entercategory.php. The $conn variable is not null and working just fine. However, i am not able to understand why, when the code in placed in a separate file (DBConnect.php), the $conn variable becomes null. Can someone please assist?
推荐答案
serverName = localhost ;
serverName="localhost";
userName = root ;
userName="root";
passWord = ;
passWord="";
这篇关于包含在另一个文件中时,连接变量为null!的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!