如何使用PHP,MySQL和mysqli_query在db中上传和保存文件?

时间:2019-01-28 00:50:10

标签: php mysql database

我正在尝试使用PHP压缩文件并将其保存在表中,但是返回失败。图片确实上传了,但是我的mysqli_query出了点问题。

HTML

<form action="server.php" enctype="multipart/form-data" method="post"
id="myForm">
          <select name="type">
            <option value="">Välj typ här</option>
            <option value="photo">Photo</option>
            <option value="video">Video</option>
            <option value="audio">Audio</option>
          </select>
          <input type="text" name="title" placeholder="Titel" class="title">
          <input type="file" name="media" class="btn">
          <input type="submit" value="Spara media" class="btn">
        </form>

Javascript:

$("#myForm").submit(function(e) {
    // Förhindrar att vi skickas iväg till en ny sida (standardhändelsen)
    e.preventDefault();
    // Hämtar formulärsdata (värde från drop-down menyn, samt filen)
    var formData = new FormData(this);

    // Gör ett ajax-anrop
    $.ajax({
        url: $(this).attr("action"), // Till adressen "server.php"
        type: $(this).attr("method"), // Med metoden "post"
        data: formData, // Vår data vi skickar med
        dataType: "JSON", // Hur vi ska tolka den data vi får tillbaka (som JSON)
        cache: false, // Vi tillåter inte att webbläsaren att cacha några resultat
        contentType: false, // Vi vill inte att jQuery ska bestämma hur vårt
        innehåll ska tolkas
        processData: false // Vi tillåter inte att jQuery att processa vår data (som strängar)
    }).done(function (data) {
        // Om vi får ett lyckat svar
        console.log(data);
    }).fail(function(data){
        // Om vi får ett misslyckat svar
        console.log(data);
    });
});

PHP:     

$servername = "*hidden*";
$username = "*hidden*";
$password = "*hidden*";
$db = new mysqli($servername, $username, $password);

if (!$db) {
 echo "Error: Unable to connect to MySQL." . PHP_EOL;
 echo "Debugging errno: " . mysqli_connect_errno() . PHP_EOL;
 echo "Debugging error: " . mysqli_connect_error() . PHP_EOL;
 exit;
}

$return = new ArrayObject();

if(isset($_FILES['media']['tmp_name'])){
$path = $_POST['type']."/";
$fileName = $path.rand().$_FILES['media']['name'];

if(move_uploaded_file($_FILES['media']['tmp_name'], $fileName)){
 $title = "";
 if(isset($_POST['title'])){
  $title = $_POST['title'];
 }
 if(mysqli_query($db, "INSERT INTO media (title, type, path) VALUES 
 ('".$title."', '".$_POST['type']."', '".$fileName."')")){
  $return['success'] = true;
  $return['path'] = $fileName;
  $return['title'] = $title;
  $return['message'] = "File uploaded and saved in db";
  echo json_encode($return);
 }else{
  $return['success'] = false;
  $return['path'] = $fileName;
  $return['title'] = $title;
  $return['message'] = "File uploaded but not saved in db";
  echo json_encode($return);
 }

 }else{
  $return['success'] = false;
  $return['message'] = "Kunde inte ladda upp filen";
  echo json_encode($return);
 }
  }

if(isset($_GET['action']) and $_GET['action'] == "getMedia"){
if(isset($_GET['type'])){
$res = mysqli_query($db, "SELECT * FROM media WHERE type = 
'".$_GET['type']."' ORDER BY id DESC");
}else{
$res = mysqli_query($db, "SELECT * FROM media ORDER BY id DESC");
}
$media = new ArrayObject();
while($row = mysqli_fetch_assoc($res)){
$m = new ArrayObject();
$m['path'] = $row['path'];
$m['type'] = $row['type'];
$m['title'] = $row['title'];
$m['timestamp'] = $row['timestamp'];
//$m['id'] = $row['id'];
$media['files'][] = $m;
}
echo json_encode($media);
}


?>

Here is the console message received:

编辑:这是将错误消息传递到控制台的位置,可以在php文件中找到

}else{
  $return['success'] = false;
  $return['path'] = $fileName;
  $return['title'] = $title;
  $return['message'] = "File uploaded but not saved in db";
  echo json_encode($return);
 }

第二次编辑。
我将此行添加到了else中:
echo(“错误说明:”。mysqli_error($ db));
产生了以下消息:
“错误描述:未选择数据库{”成功“:false,”路径“:” photo / 2969cloak.JPG“,”标题“:” Hej“,”消息“:”文件已上传但未保存在数据库中“”“” < / p>

2 个答案:

答案 0 :(得分:1)

实际上就是这么简单。我没有选择数据库,只有主机。原因是,就我而言,用户名和数据库是相同的,因为它是学校服务器。谢谢大家!

答案 1 :(得分:0)

我看不到您在哪里选择数据库。 您可以使用mysqli_select_db ($db, "Database_Name")

我通常将查询生成与查询执行分开,以帮助调试SQL中的错误。您还可以返回原始查询,并尝试直接在MySQL中运行它,例如:

$query="INSERT INTO media (title, type, path) VALUES ('".$title."', '".$_POST['type']."', '".$fileName."')";

$return['query'] =  $query;  

此外,您还可以捕获错误消息:

if(mysqli_query($db, $query)){
     //success
     $return['error'] = "success";
     ...

} else {
    $return['error'] = "Error: ". $query ."<br /> \n". mysqli_error($db) ."<br /> \n";
    ...

}