我有一个这样的脚本,其中包含我的模型中用于处理图像上传的脚本。然后我用addImage()调用该文件中的函数,如下所示:
<?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);
?>
然后,在imageUploadHandler.php中,我编写了这个函数,这个函数毫无障碍地被调用:
<?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!";
}
}
?>
我已经包含了一个“db_conn.php”脚本,这样我就可以在需要连接到数据库的地方包含db_conn.php。这是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();
}
?>
如果我将连接脚本直接内联而没有包含,则数据库已连接并且一切正常。但是,当我尝试包含外部文件(db_conn.php)时,由于某种原因,$ con变量不可用于我的imageUploadHandler.php
任何想法为什么?
答案 0 :(得分:1)
这是范围问题。除非作为参数传递或声明为global
,否则您的连接将无法在您的函数范围内使用。