MySQL不会在上传文件时将数据插入表中

时间:2013-03-06 18:26:45

标签: php mysql

我正在尝试创建一个库系统,该系统在表中为每个图像创建条目,允许脚本检索具有特定值的所有图像。目前我设法让文件上传工作,虽然它没有输入文件名和图库ID到我的表 - 它根本没有创建一行。下面是代码,任何帮助都会很棒:)!我已经弄乱了一些东西,虽然文件上传和喜欢并不是我的强项。

<?php
require "common.php";
$con = mysql_connect("localhost","$username","$password");
mysql_select_db("$dbname", $con);
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }
$id = $_GET['id'];
$query2 = mysql_query("SELECT id,title,date FROM galleries WHERE id = $id");
    if (!$query2) {
        echo 'Could not run query: ' . mysql_error();
        exit;
}
$row = mysql_fetch_row($query2);
$allowedExts = array("jpg", "jpeg", "gif", "png");
$extension = end(explode(".", $_FILES["file"]["name"]));
if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/png")
|| ($_FILES["file"]["type"] == "image/pjpeg"))
&& ($_FILES["file"]["size"] < 2000000)
&& in_array($extension, $allowedExts))
  {
  if ($_FILES["file"]["error"] > 0)
    {
        echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
    }
  else
    {
    echo "Upload: " . $_FILES["file"]["name"] . "<br>";
    echo "Type: " . $_FILES["file"]["type"] . "<br>";
    echo "Size: " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
    echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br>";

    if (file_exists("../galleries/images/" . $_FILES["file"]["name"]))
      {
      echo $_FILES["file"]["name"] . " already exists. ";
      }
    else
      {
      move_uploaded_file($_FILES["file"]["tmp_name"],
      "../galleries/images/" . $_FILES["file"]["name"]);
      $file = '["file"]["name"]';
      $sql="INSERT INTO images (url, gallery)
        VALUES
  ('$_POST[$file]','$_POST[$id]')";
  header("Location: ../../../gallery.php?id=" . $row[0]); 
  die("Redirecting to: admin.php"); 
if (!mysql_query($sql,$con))
  {
  die('Error: ' . mysql_error());
  }
      }
    }
  }
else
  {
  echo "Invalid file";
  }
?>

1 个答案:

答案 0 :(得分:0)

问题是您在执行查询之前重定向并终止了脚本:

$sql="INSERT INTO images (url, gallery)
        VALUES
         ('$_POST[$file]','$_POST[$id]')";
header("Location: ../../../gallery.php?id=" . $row[0]); 
die("Redirecting to: admin.php");
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ nothing after this gets executed
if (!mysql_query($sql,$con))
     ^^^^^^^^^^^^^^^^^^^^^^ this query will never run
   ...

你真的应该切换到PDO(或mysqli)并准备好语句以避免sql注入问题。