PHP上传文件,将文件url保存到MySQL

时间:2012-04-13 10:32:34

标签: php mysql

坚持这一点,尝试从ajax到w3schools版本的上传,但没有去。

我的_events.php脚本包含以下内容以获取文件信息:

<input name="event_image" type="file" />

我的_eventscreate.php脚本无法将文件上传到我的_gallery /目录,一旦上传,我想要将文件保存到我的数据库(参见SQL查询)。

<?php   // Get Event ID
    $location=$_GET['location'];

    // Get values from form
    $event_name=$_POST['event_name'];
    $event_description=$_POST['event_description'];
    $event_date=$_POST['event_date'];
    $event_time=$_POST['event_time'];
    $event_cost=$_POST['event_cost'];
    $event_image=$_POST['event_image'];

    // Connection to MySQL Database.
    include ('_includes/_dbconnection.php');
    include ('_includes/_dbopen.php');

    // Update Event using Event ID.

    $sql="INSERT INTO b_events (ename, edescription, edate, etime, ecost, locationid, eimage)VALUES('$event_name', '$event_description', '$event_date', '$event_time', '$event_cost', '$location', '$event_image')";
    $result=mysql_query($sql);

    if($result){
    header('Location: _events.php');
    }

    else {
    header('Location: _home.php');
    }

?>

请帮助

2 个答案:

答案 0 :(得分:0)

通过URL,我将假设您指的是文件本地副本的路径,而不是远程源位置。如果我弄错了,答案可能是“不要使用文件上传”。

当你的php脚本被执行时(除非你做了特别奇怪的事情),这意味着文件上传已经完成,文件信息(名称,大小等)存储在$ _FILE中。在您能够存储或使用其路径(或确实将其移至_gallery)之前,您需要设置该路径。 上传后,文件存储在$ _FILES [fileID] [“tmp_name”]的路径中。但是,您不能直接在此路径上操作,例如使用移动或读取操作(至少我不能在Apache2中)。

首先,您需要通过PHP的inbuit方法将该文件写入您选择的位置。例如:

move_uploaded_file($_FILES[fileID]["tmp_name"], "_gallery/".$_FILES[fileID]["name"]);

在此之后,该文件是你自己想做的,它的地址(上例中的“_gallery /".$_ FILES [fileID] [”name“])只是另一个PHP字符串。

如果通过URL表示该文件的外向地址(有人将其放入浏览器中以获取该文件),那么您需要自己构建它。在最简单的情况下,该文件位于webroot中,这意味着连接到您刚刚编写的文件的相对路径。如果您不想使用硬编码的基本网址,则$_SERVER中的值可能对您有用。

答案 1 :(得分:0)

你不能使用$ event_image = $ _POST ['event_image'];获取上传的文件。

要访问上传的文件,您必须使用$ _FILES [$ name],其中$ name是以下名称:

<input type="file" name="something" />

还要确保您的表单有method =“post”和enctype =“multipart / form-data”。

$ _ FILES [$ name]本身将是一个数组(关联数组),其中包含键:

  • 名称
  • 尺寸
  • tmp_name的值
  • 错误

文件成功上传后(使用$ _FILES [$ name] ['error'] == UPLOAD_ERR_OK进行测试),您需要将其移至首选位置。

移动文件后(使用move_uploaded_file()),您可以获取其名称,并将值分配给$ event_image。然后将其保存到数据库中。

有关详细信息,请read this

相关问题