未定义的索引PHP第12行

时间:2015-10-31 20:34:14

标签: php mysql sql database

尝试通过php上传论文。它只是存储在我的本地驱动器上。我一直在第12行得到未定义的索引。不知道为什么,我发誓它之前正在工作。我该怎么做才能解决这个问题?请帮忙。

<?php
require_once("constants.php"); //Now constants will be accessible

$link = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
mysqli_set_charset($link, 'utf8');
if (!$link) {
    die("Database connection failed: " . mysqli_error($connection));
}
//Use array to not repeat code
$post_vars = array('paper', 'author1', 'author2', 'author3', 'university', 'contact', 'file');
foreach($post_vars as $key) {
     $$key = mysqli_real_escape_string($link, $_POST[$key]);
    //For example now there is a variable $firstname that you can use
}

$sql = "INSERT INTO papers (paper, author1, author2, author3, university, contact, file) VALUES ('$paper', '$author1', '$author2', '$author3', '$university', '$contact', '$file');";
$result = mysqli_query($link, $sql);
mysqli_close($link);

 if(isset($_POST['submitButton'])){
    $name       = $_FILES['file']['name'];  
    $temp_name  = $_FILES['file']['tmp_name'];  
    if(isset($name)){
        if(!empty($name)){      
            $location = 'C:/xampp/htdocs/Proj-1-1/uploads/';      
            if(move_uploaded_file($temp_name, $location.$name)){
                echo 'uploaded';
            }
        }       
    }  else {
        echo 'please uploaded';
    }
}
?>

1 个答案:

答案 0 :(得分:3)

您的参数不一定在$_POST数组

foreach($post_vars as $key) {
    if (isset($_POST[$key])){
        $$key = mysqli_real_escape_string($link, $_POST[$key]);
        //For example now there is a variable $firstname that you can use
    }
}

编辑:

看看这个:

$name       = $_FILES['file']['name'];
if(isset($name))

已定义变量$name,您无需检查isset($name),因为您已在上一行($name = ...)中对其进行了定义。您可以检查它是否不是null

请注意,在$name = $_FILES['file']['name'];行中,您实际上并不知道$_FILES是否包含file索引以及$_FILES['file']是否具有name索引。< / p>

您可以验证它:

$name = isset($_FILES['file']) && isset($_FILES['file']['name']) ? $_FILES['file']['name'] : '';