使用标题和商店标题上传图片&会话用户名到数据库

时间:2014-09-23 17:19:22

标签: php sql upload

我想实现一个简单的图片上传器,用于存储标题,用户登录($ _SESSION ['用户名'])以及保存文件的路径。

会话正在运行,代码正确,数据库表存在,但它只写了'路径'价值,用户名'和#cap;'在数据库上保持空白。

这是上传代码:

if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/jpg")
|| ($_FILES["file"]["type"] == "image/pjpeg")
|| ($_FILES["file"]["type"] == "image/x-png")
|| ($_FILES["file"]["type"] == "image/png"))
&& ($_FILES["file"]["size"] < 5000000)
&& in_array($extension, $allowedExts)) {
if ($_FILES["file"]["error"] > 0) {
echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
} else {
if (file_exists("upload/" . $_FILES["file"]["name"])) {
  echo $_FILES["file"]["name"] . " already exists. ";
} else {
  move_uploaded_file($_FILES["file"]["tmp_name"],
  "upload/" . $_FILES["file"]["name"]);
  $caption = $_POST['caption'];
    $uploaderUsername = $_SESSION['username'];
    $path = "upload/" . $_FILES['file']['name'];
    mysql_connect("localhost","root","") or die(mysql_error());
    mysql_select_db("mydb") or die(mysql_error());
    mysql_query("INSERT INTO images (caption,username,path) VALUES
('$caption','$uploaderUsername','$path')");
  header('Location: members.php');
}
}
} else {
echo "Invalid file";
}

我想这部分有问题:

  $caption = $_POST['caption'];
    $uploaderUsername = $_SESSION['username'];
    $path = "upload/" . $_FILES['file']['name'];
    mysql_connect("localhost","root","") or die(mysql_error());
    mysql_select_db("mydb") or die(mysql_error());
    mysql_query("INSERT INTO images (caption,username,path) VALUES
('$caption','$uploaderUsername','$path')");
  header('Location: members.php');

1 个答案:

答案 0 :(得分:1)

添加到我上面的注释

“在尝试访问会话变量之前,我没有看到你调用session_start()。(这恰好是你没有得到的两个变量之一:O)。并且在你的表单中确保你是为标题输入“

设置name ='caption'

使用您提供的代码来实现您希望按照

的方式执行操作的标题
<form action="upload_file.php" method="post" enctype="multipart/form-data"> 
    <label for="file">Filename:</label> 
    <input type="file" name="file" id="file"><br> 
    <label for="caption">Caption: </label>
    <input type="text" id="caption" name="caption" placeholder="Add a caption here"><br>        
    <input type="submit" name="submit" value="Submit"> 
</form>