title: How to upload and save a file in db using PHP, MySQL and mysqli_query?
body: <p>I'm trying to ulpoad a file using PHP and save it in a table, but it returns as failed. The picture does upload, but something is wrong with my <code>mysqli_query</code> or something.</p>
  
  <p>HTML</p>
  
  <pre><code>&lt;form action="server.php" enctype="multipart/form-data" method="post"
  id="myForm"&gt;
            &lt;select name="type"&gt;
              &lt;option value=""&gt;Välj typ här&lt;/option&gt;
              &lt;option value="photo"&gt;Photo&lt;/option&gt;
              &lt;option value="video"&gt;Video&lt;/option&gt;
              &lt;option value="audio"&gt;Audio&lt;/option&gt;
            &lt;/select&gt;
            &lt;input type="text" name="title" placeholder="Titel" class="title"&gt;
            &lt;input type="file" name="media" class="btn"&gt;
            &lt;input type="submit" value="Spara media" class="btn"&gt;
          &lt;/form&gt;
  </code></pre>
  
  <p>Javascript:</p>
  
  <pre><code>$("#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);
      });
  });
  </code></pre>
  
  <p>PHP:
      
  
  <pre><code>$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);
  }
  
  
  ?&gt;
  </code></pre>
  
  <p><a href="https://i.stack.imgur.com/xDuiy.jpg" rel="nofollow noreferrer">Here is the console message received:</a></p>
  
  <p>Edit: This is where the error message is delivered to the console, found in the php file</p>
  
  <pre><code>}else{
    $return['success'] = false;
    $return['path'] = $fileName;
    $return['title'] = $title;
    $return['message'] = "File uploaded but not saved in db";
    echo json_encode($return);
   }
  </code></pre>
  
  <p><strong>Second Edit.</strong><br> I added this line to my else:<br>
  echo("Error description: " . mysqli_error($db));<br>
  Which produced the following messsage:<br>
  "Error description: No database selected{"success":false,"path":"photo/2969cloak.JPG","title":"Hej","message":"File uploaded but not saved in db"}"</p>