Avoid PDO duplication in image upload

Asked

Viewed 47 times

0

In this upload code. The class uploads an audio. Everything works well, but, I do not know how to do so that "identify" and "id_user" can manage the upload and restrict to only when these two are different or is "empty", the upload is performed. There is the Upload class and the command before Upload. Below are the codes.

(01) This code is on the form page

<br><br>
<?php
require_once 'classes/Upload.class-pdo2.php';
require_once 'classes/Funcoes.class.php';

$objUp = new Upload();
$objFc = new Funcoes();

if(isset($_POST['btEnviar'])){
    $objUp->queryInsert();
}

if(isset($_POST['btAlterar'])){
    $objUp->queryUpdate();
}

if(!empty($_GET['acao'])){
    switch($_GET['acao']){
        case 'edit': $slt = $objUp->querySelecionar($_GET['id']); break;
        case 'delet': $objUp->queryDelete($_GET['id']); break; 
    }
}
?>

//<br><br>
<?php<br>
require_once "Conexao.class-pdo.php";<br>
require_once "Funcoes.class.php";<br><br>
class Upload{<br><br>
    //ATRIBUTOS PRIVADOS<br><br>
    private $con;<br>
    private $objfc;<br>
    private $idUploadArquivo;<br>
    private $tipo;<br>
    private $id_user;<br>
    private $legenda;<br>
    private $identifica;<br>
    private $arquivo;
<br><br><br>
    //CONSTRUTOR<br>
    public function __construct(){<br>
        $this->con = new Conexao();<br>
        $this->objfc = new Funcoes();<br>
    }<br><br>

    //METODOS MÁGICOS<br><br>
    public function __set($atributo, $valor){<br>
        $this->$atributo = $valor;<br>
    }<br>
    public function __get($atributo){<br>
        return $this->$atributo;<br>
    }<br>

    <br><br>

    /**<br>
     1º PARTE (VARIAVEIS E TRY-CATCH) - <br>
     O ESSA PARTE SEM FAZER O CADASTRO DAS INFORMACOES DO UPLOAD<br>
    **/<br>



    public function queryInsert(){<br>
        try{<br>
            $this->aula = $_POST['aula'];<br>
            $this->identifica = $_POST['identifica'];<br>
            $this->id_user = $_POST['id_user'];<br>
            $this->legenda =date("HisdmY");<br>
            $arquivo = $_FILES['arquivo'];<br>
            $tamanho = 5000000; //5MB<br><br>
            //2º PARTE (VERIFICANDO A EXISTENCIA DO ARQUIVO E FAZENDO A VALIDACAO DO MESMO COM TRÊS CONDIÇÕES)<br><br>
            if(!empty($arquivo['name'])){<br>
                //VALIDANDO O TIPO DE IMAGEM<br>
                //echo $arquivo['type'];<br>
                if(!preg_match('/^(audio)\/(mpeg|mp3)$/', $arquivo['type'])){<br>
                    $error = '<script type="text/javascript">alert("INSERT - Somente podem ser enviados arquivos (MP3)");</script>';<br>
                }<br>

                <br><br>
                //VALIDANDO O TAMANHO DO ARQUIVO<br><br>
                if($arquivo['size'] > $tamanho){<br>
                    $error = '<script type="text/javascript">alert("INSERT - O áudio enviado extrapola o tamanho permitido");</script>';<br>
                }<br><br>


                //3º PARTE (ALTERANDO O NOME DO ARQUIVO E ENVIANDO PARA PASTA QUE LHE FOI DESTINADA)<br><br>                        
                if(count($error) == 0){<br>
                    $ext = pathinfo($arquivo['name']);<br>
                    $nome_imagem = $this->objfc->normalizaString($this->legenda).'.'.$ext['extension'];/**/<br>
                    $legenda = 'legenda';/**/<br>

                    <br><br>
                    $caminho_imagem = 'audios/'.$nome_imagem;<br>
                    $legenda = 'legenda';<br>
                    move_uploaded_file($arquivo['tmp_name'], $caminho_imagem);<br><br>
                    //CADASTRANDO AS INFORMAÇÕES
                    <br><br>

                    $cst = $this->con->conectar()->prepare("INSERT INTO `aula_upload_arquivos` (`aula`,`identifica`,`id_user`,`legenda`, `arquivo`) VALUES (:aula,:identifica,:id_user, :legenda, :arquivo)  ;");<br>
                    $cst->bindParam(':aula', $this->objfc->tratarCaracter($this->aula, 1), PDO::PARAM_STR);<br>
                    $cst->bindParam(':identifica', $this->objfc->tratarCaracter($this->identifica, 1), PDO::PARAM_STR);<br>
                    $cst->bindParam(':id_user', $this->objfc->tratarCaracter($this->id_user, 1), PDO::PARAM_STR);<br>
                    $cst->bindParam(':legenda', $this->objfc->tratarCaracter($this->legenda, 1), PDO::PARAM_STR);<br>
                    $cst->bindParam(':arquivo', $nome_imagem, PDO::PARAM_STR);<br>
                    if($cst->execute()){<br>
                        header('Location:'.$_SERVER['PHP_SELF'].'?'.$_SERVER['QUERY_STRING']);<br>
                        <br>
                    }else{<br>
                        //Erro de falha no programa//<br>
                        //header('location: http://localhost/definitivo/erro.php');<br>
                        echo '<script type="text/javascript">alert("Error: '.$ex->getMessage().'");</script>';<br>
                    }<br>
                }else{<br>
                    echo $error;<br>
                }<br>
            }else{<br>
                echo '<script type="text/javascript">alert("Escolha o arquivo para Upload");</script>';<br>
            }<br>
        }catch(PDOException $ex){<br>
            echo '<script type="text/javascript">alert("Error: '.$ex->getMessage().'");</script>';<br>
        }<br>
    }<br>

}<br><br>
?><br>
  • You’re just registering, do a validation, a select in BD. If return > 1 is pq you already have the data saved, then do update if not insert.

  • Exactly, that’s the problem. I lack enough experience to be able to do this action. I needed an example within this programming.

  • I’m more than 2 weeks into this problem. :-(

2 answers

0

PROBLEM SOLVED:

01) As indicated by @Acco, UNIQUE was made for one of the fields 02) In the Information Register, a data has been inserted inside the field that will always be unique, using the user name and his ID.

0

You can do something similar to this. As you did not specify exactly what you need I used as an example the lesson column

$aula= "exemplo";
$stmt = $pdo->prepare("SELECT * FROM aula_upload_arquivos WHERE aula=?");
$stmt->execute([$aula]); 
$exec= $stmt->fetch();

if ($exec) {
   // Existe aula, então faz o (update)
} else {
   // Não existe aula então cria uma nova (insert)
} 
  • Thank you, I’ll try to follow that logic

  • William, thank you for your willingness. But, as you quoted, I was not very clear in my explanation. 1) There can be no duplication, 2) Class code greatly restricts actions that can be done within this code. Sometimes he writes something, and the class just ignores it. 3) There is another part of the code that controls the whole class system, maybe it would be better to insert here too

  • Will I include the full code <br><br><br> <? php require_once 'classes/Upload.class-pdo2.php; require_once 'classes/Functions.class.php'; $objUp = new Upload(); $objFc = new Functions(); if(isset($_POST['btEnviar'])){ $objUp->queryInsert(); } if(isset($_POST['btAlterar'])){ $objUp->queryUpdate(); } if(!Empty($_GET['acao'])){ switch($_GET['acao']){ case 'Edit': $slt = $objUp->querySelecting($_GET['id']); break; case 'delet': $objUp->queryDelete($_GET['id']); break; } } ?>

  • sorry, I do not know how to post here

  • Can’t put in comments, edit the question.

  • I hope you’ve improved on the question. -P

  • Bacco, Why do not you take Advantage of it and Answer the Question? An IF loop was made with an MSQLI Response and Accurate in PDO. Another Question, about CLASSES, IF, INSERT and also no Answer. Why not help, Instead of Hinder?

  • is this action possible? $identifies = ($_POST['identifies'] + $_POST['id_user']) ;

Show 3 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.