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();
}
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);
}
?>
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?
EDIT: The function is called as follows:
if(isset($_POST["btnCreateCategory"]))
{
insertCategory($_POST["txtCategoryName"],$_POST["txtCategoryDescription"]);
}
EDIT:
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?