PHP DB连接变量在Include上不可用
我有一个这样的脚本,它在我的模型中包含一个用于处理图像上传的脚本。然后,我使用addImage()调用该文件中的一个函数,如下所示:PHP DB连接变量在Include上不可用,php,Php,我有一个这样的脚本,它在我的模型中包含一个用于处理图像上传的脚本。然后,我使用addImage()调用该文件中的一个函数,如下所示: <?php include '../model/imageUploadHandler.php'; $imgTitle = $_POST["image_title"]; $imgDescr = $_POST["image_description"]; $target_path = "../images/"; $file
<?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!";
}
}
?>
这是一个范围问题。除非作为参数传入或声明为
global
,否则您的连接在您的功能范围内将不可用。那么,首选或标准解决方案是什么?声明一个全局变量是混乱的,还是这或多或少是标准的?全局变量应该谨慎使用,这样会很难管理。但是有些东西,比如数据库连接,可以在应用程序中全局使用,所以使用全局连接是有意义的。一些框架建立了如何在框架内完成的首选项(Zend framework使用全局注册表),但这最终是您的选择。因此,我现在将$con声明为全局$con,但它仍然不可用。我应该使用$\u GLOBALS[]关联数组吗?您需要在函数中指定为global$con
<?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();
}
?>