Save combobox value when uploading files?

Asked

Viewed 139 times

0

Good afternoon. I started this week in a PHP development company. I need to include a combobox on a page that uploads files. The upload already works and is being used.

** I would like help to record the selected value in the combobox in the same file table (which the client chose to upload). This combobox shows the "File Category" and will serve to sort the client’s images/documents.

.php // File containing the combobox and also the button to upload the files.

<div class="form-group"> Categoria do Arquivo
        <form name="formCatArq" id="formCatArq" method="post" >
          <select class="form-control" style="width:40%" name="arqcat_codigo" id="arqcat_codigo"  >
            <option value="-1" selected="selected">Selecione a Categoria do Arquivo</option>
            <?php										  
 //CARREGA LISTA DE CATEGORIAS										 
$sql_gru = "select * from arquivos_categorias $sql_cat where arqcat_ativo ='S'  order by arqcat_titulo asc ";
$qry_gru = mysql_query($sql_gru);						 
if (mysql_num_rows($qry_gru) > 0) {
	while ($row = mysql_fetch_array($qry_gru)) {?>
            <option value="<?php echo $row['arqcat_codigo']?>" <? if ($marqcat_codigo == $row['arqcat_codigo']) {echo 'selected="selected"'; } ?>> <?php echo $row['arqcat_titulo']; ?> </option>
            <?php }
}?>
          </select>
          <label>
            <input type="submit" name="btnEnviar" id="btnEnviar" value="Filtrar sua busca:"  />
          </label>
        </form>
      </div>
     
// Botão para realizar o "Upload"
      <div id="mulitplefileuploader_arquivos">Upload</div>

Index.php // contains script to pick up the combobox value and in the sequence calls the function "envia_value" in an attempt to load the combobox value together with the upload function. I am trying to send the variable "$arqcat" along with the parameter "url:" of the variable "settings_arq", but this value does not arrive on the page "upload_files.php" that makes the insertion in the database.

<script>
$(function() {
    $('#arqcat_codigo').change(function(){
       var tip = $("#arqcat_codigo").val();
       if (($('#arqcat_codigo').val() == '-1') || (tip == '-1')) 
       {
            alert('Selecione a Categoria do Arquivo');
         
        }
        else {
		  envia_valor(tip);
			}
    });
});
</script> 

<script>	
function envia_valor(tip) {
	 $arqcat = tip;
	 $(document).ready(function(){
	 // alert($arqcat);
var settings_arq = {
			url: "upload_arquivos.php?cod=<?=$codigo?>&usucatcod=<?=$usucat?>&arqcatcodigo=<?=$arqcat?>",
					method: "POST",
					fileName: "myfile",
					multiple: true,
					showProgress: true,
					showStatusAfterSuccess: true,
					dragDropStr: "<span><b>Selecione os arquivos para upload23332</b></span>",
					onSuccess:function(files,data,xhr)
					{
						$("#status").html("<font color='green'>Upload realizado com sucesso</font>");
						location.reload();
					},
					onError: function(files,status,errMsg)
					{		
						$("#status").html("<font color='red'>Falha no upload</font>");
					}
				}
				$("#mulitplefileuploader_arquivos").uploadFile(settings_arq);
});
};
</script> 

upload_php files // takes the parameters and generates sql.

<?php
if(isset($_FILES["myfile"]))
{
	$ret = array();
	$error =$_FILES["myfile"]["error"];
   {
    
    	if(!is_array($_FILES["myfile"]['name'])) //single file
    	{
       	 	
			$arquivo = $_FILES["myfile"];
			$nome_temp = $arquivo["tmp_name"];
			$nome_arquivo =  $cod . "-" . $arquivo["name"];
			$nome_arquivo = str_replace(' ', '', $nome_arquivo);
			move_uploaded_file($_FILES["myfile"]["tmp_name"],$output_dir. $nome_arquivo);
       	 	      	$ret[$arquivo]= $output_dir.$arquivo;
			$sql = "insert into arquivos (usu_codigo, arqcat_codigo, usucat_codigo, arq_legenda, arq_arquivo, arq_data, arq_imagem)  values($cod, '$arqcatcodigo', '$usucatcod', '$arquivo[name]','$nome_arquivo',curdate(),'N')";
			$post = mysql_query($sql);
			$codigo = mysql_insert_id();
			$ext = strxchr($nome_arquivo, ".", 1, 1);
			$ext = substr(strtolower($ext[1]),1);
				if ($ext=='jpg' || $ext=='jpeg' || $ext=='png') {
					GerarImagens($nome_arquivo, 200, 'thumb_');
					GerarImagens($nome_arquivo, 227, 'gal_');
					$sql2 = "update arquivos set arq_imagem='S' where arq_codigo=$codigo";
					$qry2 = mysql_query($sql2);
				}
			
    	}
    	
    }  
    echo json_encode($ret); 
}
?>

  • "<div id="mulitplefileuploader_arquivos">Upload</div>" That’s a button?

  • I didn’t write the code, I’m adapting the combobox on the form. I don’t know how to explain it, but this div does the upload button (I think it must be Jquery). There is no input button, that’s all. The name of this div appears on the index.php page, where some parameters are assigned that will be sent to the upload_files.php page (which will run sql). I am trying to pass the value of the combobox on the "settings_arq" function on the index page, so that it is added in sql and save at the time the user chooses the file to upload.

  • Was malz ae , I saw there the jquery makes the button... I see here I can help

  • If you uncomment the alert($arqcat);, it shows the selected option?

  • Yes.. until then Alert displays the variable. But when I try to call inside the "var settings_arq" it does not reach the target page. I tried to send the $arqcat variable through the line insira o código aquiurl: "upload_files.php? Cod=<?= $codigo? >&usucatcod=<?= $usucat? >&arqcatcodigo=<?= $arqcat? >", , but it didn’t work. The $usucat and $code variables are passed when the user clicks the upload screen menu.

  • I tried to send the $arqcat variable through the line url: "upload_arquivos.php?cod=<?=$codigo?>&usucatcod=<?=$usucat?>&arqcatcodigo=<?=$arqcat?>", , but it didn’t work. The $usucat and $code variables are passed the moment the user clicks the uploads screen menu.

  • But does it give an error message? After you do the test click on display source code and see if there is an error?

  • Since I am not able to send the value of the combobox together with the variable "settings_arq", I am thinking of leaving the combobox and after uploading the user click on a new button that will make the insertion(change) in that image/file record in the database and save in the corresponding field the value of the combobox. But I run a risk that the user leaves the screen without registering the category of the file (combobox).

  • Face this must be a silly mistake... I have a similar form here... But I do not advise you to give up, unless there is no other way... Try to start a process equal to that of 0, with as little information as possible ...part by part...

  • Good morning Magichat. The "send value" function receives the value of the combobox, because I was using Alert to test. The problem is that I need to send this value along with the "var_settings" variable that is generated by uploading the file. This variable sends the data to the upload_files page, where it has the sql for insertion. Do you know any way to insert a value of one variable within the attributes of another variable ?

  • I tried to send the value through the url, but of the various ways I tested, none worked. I tried to do "value: $arqcat," inside the attributes of the variable "settings_arq", but it also didn’t work.

  • it is really necessary to use ajax, or you just want to write the file and category in the database?

  • I need to save the upload file and its category in the database. The way it will be done is not the main point. In the latter case, I will put a combobox in the list of files that the user uploaded and a button to make a change to the record by inserting the category.

Show 8 more comments

1 answer

0

@Allan I do this way, then you adapt to your code.

php form.

<form action="insere.php" method="POST" enctype="multipart/form-data">
<select name="cat">
<?php
//conexão
include 'conect.php';
//seleciona as categorias
$sql = "select nome_carac from carac where nome_carac is not null";
$exec = $con->query( $sql ) or exit( $con->error );                      
$i = 1;
while ( $f = $exec->fetch_object() )
{
$cats[$i]['nome_carac'] = $f->nome_carac;
$i++;
}
//gera a lista de opcoes
foreach ($cats as $key => $value) {
echo "<option value='{$value['nome_carac']}' > {$value['nome_carac']}</option></br>";
}
$con->close();
?>
</select></br>

<input type="file" name="files[]" multiple/>

<input type="submit"/>

</form>

php insert.

include 'conect.php';
// muda o banco "teste"
mysqli_select_db($con,"test_stack");
//trata imagem
if(isset($_FILES['files'])){
$errors= array();
//pega as informacoes das imagens
foreach($_FILES['files']['tmp_name'] as $key => $tmp_name ){
    $file_name = $key.$_FILES['files']['name'][$key];
    $file_size =$_FILES['files']['size'][$key];
    $file_tmp =$_FILES['files']['tmp_name'][$key];
    $file_type=$_FILES['files']['type'][$key];  
    if($file_size > 2097152){
        $errors[]='Tamanho máximo do arquivo : 2 MB';
    }

$select_opt =  $_POST['cat'];

$sql="INSERT INTO _stack (nome_img, nome_cat) VALUES ('$file_name','$select_opt ')";

    $desired_dir="user_data";
    if(empty($errors)==true){
        if(is_dir($desired_dir)==false){
            mkdir("$desired_dir", 0700);// Cria o diretorio para imagens
        }
        if(is_dir("$desired_dir/".$file_name)==false){
            move_uploaded_file($file_tmp,"$desired_dir/".$file_name);
        }else{                                  //Renomeia se existe
            $new_dir="$desired_dir/".$file_name.time();
             rename($file_tmp,$new_dir) ;               
        }
     mysqli_query($con, $sql);          
    }else{
            print_r($errors);
    }
}
if(empty($error)){
    echo "Success";
}
}
$con->close();

Notice that I am only entering the name of the images and the category that comes from select. See if it helps anything comments that agent adjusts.

Browser other questions tagged

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