Reputation: 2541
I have a script like so, which includes a script in my model for handling image uploads. I then call a function in that file with addImage(), like so:
<?php
include '../model/imageUploadHandler.php';
$imgTitle = $_POST["image_title"];
$imgDescr = $_POST["image_description"];
$target_path = "../images/";
$filename = basename( $_FILES['file']['name']);
$target_path = $target_path . $filename;
addImage($imgTitle, $imgDescr, $filename);
?>
Then, in the imageUploadHandler.php, I write the function, which is called without a hitch:
<?php
include('./db_conn.php');
function addImage($title, $description, $target_path)
{
if(move_uploaded_file($_FILES['file']['tmp_name'], $target_path))
{
$sql = "INSERT INTO image_data (filename, title, description) VALUES ('$target_path','$title','$description')";
echo $sql;
if (!mysqli_query($con, $sql))
{
die('Error: ' . mysqli_error());
}
echo "1 record added";
echo "The file " . basename( $_FILES['file']['name']) . " has been uploaded";
echo $title;
echo $description;
}
else
{
echo "There was an error uploading the file, please try again!";
}
}
?>
I have included a "db_conn.php" script, such that I can include the db_conn.php wherever I need to connect to the databse. Here is the db_conn.php
<?php
// Create connection
$con = mysqli_connect("","root","root", "image_info");
// Check connection
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
?>
The database is connected to and everything works well if I put the connection script directly inline without an include. However, when I try to include an external file (db_conn.php), then for some reason the $con variable is not available to my imageUploadHandler.php
Any ideas why?
Upvotes: 0
Views: 125
Reputation: 19563
This is a scope problem. Unless passed in as an argument or declared global
your connection will not be available in your function scope.
Upvotes: 1