简体   繁体   中英

How to save a file name in the MySQL database?

I have developed this code below to the user upload a file and save the name of this file in the database, to be able to access it later, the upload is done normally, it goes to the designated folder, but the name is not saved in the database, does anyone know what's wrong with the code? Especially below the move_uploaded_file, because so far it works, then it goes wrong.

<?php
if (isset($_POST['enviar'])) {
$arq = $_FILES['arquivo']['name'];

$arq = str_replace(" ", "_", $arq);
$arq = str_replace("ç", "c", $arq);

if (file_exists("uploads/$arq")) {
  $a = 1;

  while (file_exists("uploads/[$a]$arq")) {
    $a++;
  }

  $arq = "[".$a."]".$arq;
}

if (move_uploaded_file($_FILES['arquivo']['tmp_name'], 'uploads/'.$arq)) {
  $objDb = new db();
  $link = $objDb->conecta_mysql();
  $sql = "insert into arquivos (email_vol, nomearq) values ('$email', '$arq')";
  if (mysqli_query($link, $sql)){
    echo 'Plano de aula 1 enviado com sucesso!';
  } else {
    echo (mysqli_error($link));
    echo 'Erro ao enviar o plano de aula!';
  }

} else {
  echo "Nenhum arquivo selecionado!";
}

}
?>

That is the code used to connect with the database:

class db {
//host
private $host = 'localhost';

//usuario
private $usuario = '111111';

//senha
private $senha = '11111111';

//banco de dados
private $database = 'dsfadsfasd';

public function conecta_mysql(){

//criar a conexão
$con = mysqli_connect($this->host, $this->usuario, $this->senha, $this->database);

//ajustar a charser de cominicação entre a aplicação e o bd
mysqli_set_charset($con, 'utf8');

//verificar se houve erro de conexão
if (mysqli_connect_errno()) {
    echo 'Erro ao tentar se conectar com o banco de dados'.mysqli_connect_error();
}

return $con;
}
}
?>

Don't have the privilege to comment right now but shouldn't this be like this plus you don't have a semicolon at the end of your sql script

$sql = "insert into arquivos (email_vol, nomearq) values ('" . $email . "', '" 
 .$arq . "');";

and also this

if (file_exists("uploads/" . $arq)) {
  $a = 1;

  while (file_exists("uploads/". $a . ".". $arq)) {
    $a++;
  }

  $arq = $a.".".$arq;
}

with a full stop between your file number and name

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM