开发者

PHP upload errors

开发者 https://www.devze.com 2023-04-08 04:59 出处:网络
I have an upload script that\'s causing me some problems and I can\'t for the life of me figure out why. Here\'s the php code:

I have an upload script that's causing me some problems and I can't for the life of me figure out why. Here's the php code:

mysql_connect('localhost', 'root', '');
mysql_select_db('uploads');

if (isset($_FILES["file"]["type"]) && isset($_FILES["file"]["size"])) {
if (($_FILES["file"]["type"] == "image/png")) {
    if ($_FILES["file"]["size"] < 500120) {
        if ($_FILES["file"]["error"] > 0) {
            echo $_FILES["file"]["error"];
        } else {                         
            if (file_exists("uploads/" . $_FILES["file"]["name"])) {
          开发者_如何学运维     echo $_FILES["file"]["name"] . " already exists. ";
            } else {
                move_uploaded_file($_FILES["file"]["tmp_name"], "uploads/" . $_FILES["file"]["name"]);
                $name = $_FILES["file"]["name"];
                mysql_query("INSERT INTO uploads (name) VALUES ('$name')");                 
                if (isset($_POST['title']) && isset($_POST['desc'])) {
                    $title = $_POST['title'];
                    $desc = $_POST['desc'];
                    mysql_query("INSERT INTO uploads (title, desc) VALUES ('$title', '$desc')");
                    echo $title;
                    echo $desc;
                }                  
            }
        }
    } else {
        echo "File is too big";
    }
} else {
   echo "Wrong file type";
}
}

I know that my file paths and form input are correct and if I echo the $title or $desc variables they return with the correct values. My problem is this: for some reason it won't enter the $title and $desc values into the database. The first mysql query works fine but not the second. Any idea why?


This is likely because desc is a MySQL reserved keyword, and it must be enclosed in backquotes in your query statement. Always check mysql_error() to find the cause of a failed query.

$success = mysql_query("INSERT INTO uploads (title, `desc`) VALUES ('$title', '$desc')");
if (!$success) echo mysql_error();

Please also escape $title and $desc before insert, as they are coming directly from $_POST.

$title = mysql_real_escape_string($_POST['title']);
$desc = mysql_real_escape_string($_POST['desc']);

And do the same for $name in the earlier query:

$name = mysql_real_escape_string($_FILES["file"]["name"]);


You are creating 2 records in the uploads table, for 1 file. Probably the name column is set to not null, and this causes second query not to work. It have to be:

$name = mysql_escape_string($_FILES["file"]["name"]);
$title = isset($_POST['title'])?mysql_escape_string($_POST['title']) : '';

$desc = isset($_POST['desc'])?mysql_escape_string($_POST['title']) : '';

mysql_query("INSERT INTO uploads (`name`, `title`, `desc`) VALUES ('$name', $title, $desc)");
0

精彩评论

暂无评论...
验证码 换一张
取 消