Insert Image into a table already created

Asked

Viewed 696 times

-1

I have two tables - alunos(id, nome, email...) and fotos(id, imagem, id_aluno). I need to add an image to each student already created.

I had an idea to make a select that shows all students and then, selecting, add the image one by one.
I would like you to help me add the photo using foreign key.

PS: I’m new in php, but I already made a method to add the photos, I want to know now how to add relating the photo to the student that appears in select.

Thanks in advance.

//<?php


$conn = @mysql_connect("localhost", "......", ".......") or die ("Problemas na conexão.");
$db = @mysql_select_db("bancoTeste", $conn) or die ("Problemas na conexão");

    ini_set('default_charset','UTF-8');
    error_reporting(E_ALL);
    ini_set("display_errors", 1);


if($_POST['cadastrar']){

    // Recupera os dados dos campos
    $foto = $_FILES["foto"];



        // Verifica se o arquivo é uma imagem
        if(!preg_match("/^image\/(pjpeg|jpeg|png|gif|bmp)$/", $foto["type"])){
           $error[1] = "Isso não é uma imagem.";
        } 

        // Se não houver nenhum erro
        if (count($error) == 0) {

            // Pega extensão da imagem
            preg_match("/\.(gif|bmp|png|jpg|jpeg){1}$/i", $foto["name"], $ext);

            // Gera um nome único para a imagem
            $nome_imagem = md5(uniqid(time())) . "." . $ext[1];

            // Caminho de onde ficará a imagem
            $caminho_imagem = "fotosMex/" . $nome_imagem;

            // Faz o upload da imagem para seu respectivo caminho
            move_uploaded_file($foto["tmp_name"], $caminho_imagem);



            // Insere os dados no banco
            $inserir = mysql_query("SELECT id FROM alunos");
            $inserir = mysql_insert_id();

            $sql = mysql_query("INSERT INTO fotosTeste VALUES('', '".$nome_imagem."', '".$inserir."')");



            // Se os dados forem inseridos com sucesso
            if ($sql){
                echo "Você foi cadastrado com sucesso.";
            }else{

                echo "nao enviada";
            }
        }

        // Se houver mensagens de erro, exibe-as
        if (count($error) != 0) {
            foreach ($error as $erro) {
                echo $erro . "<br />";
            }
        }

}

?>

//<!--<!DOCTYPE html>
// <html lang="pt-br">
 //<head>
// <meta charset="utf-8"/>
 /  <title>Cadastro</title>
 /</head>
 /<body>



 //<h1>Cadastro de Usuário</h1>
 //<form action="<?php echo $_SERVER['PHP_SELF'] ?>" method="post" //enctype="multipart/form-data" name="cadastro" >

 //<label>Selecione um aluno</label>

 //<select name="alunos">

 //<option>Alunos</option>

 //<?php 
 //$sql = mysql_query("SELECT * FROM alunos");

 //while ($aluno = mysql_fetch_object($sql,MSQL_ASSOC)) { ?>

            <option value="<?php $aluno['id'] ?>"

            <?php if ($aluno['id'] == $_POST['alunos']) { 
                echo "selected";
            }  ?>>

            <?php echo $aluno['pess_nome'];  ?>


            </option>
 //<?php } ?>

  //</select>


            <input type="file" name="foto"/>
            <input type="submit" name="cadastrar" value="Cadastrar"/><br/>



 </form>
 </body>
 </html> -->

2 answers

0

"want to know now how to add relating the photo to the student that appears in select" I’m understanding that your question is specifically how to pass the student id to the php page.

When creating your select use each student’s id in the value attribute.

<select id="alunos">
  <option value="1">Aluno-1</option>
  <option value="2">Aluno-2</option>
  <option value="3">Aluno-3</option>
  <option value="4">Aluno-4</option>
</select>

When you press the button to record the changes use the following javascript to send this id to your php page. I’m assuming you won’t use AJAX.

//Usando jQuery
<script>
    $(function(){

        $(document).on("click keydown", "#btn_sendFile", function(e){
         e.preventDefault();//Previne o comprtamento send by default
         var alunoID = $("#alunos").val();
         //alert(alunoID);//Para teste
         window.location = "minhaPage.php?alunoIDjS="+alunoID;//alunoIDjS é uma variavel para ser usada na proxima pagina, minhaPage.php
      }); //End of $(document).on("change", ...    
    });//End of $(function(){
</script>  

On your php page use:

<?php

$alunoId = $_POST["alunoIDjS"]; //Vai recuperar o valor do alunoID

//O seu código para recuperar a foto

//Use $alunoId no seu sql....

?>
  • I didn’t understand very well, my page already contains all the code.

  • in addition, as I do at the time of the Insert?

  • See this part of your code: "// Enter the data in the database". You do not need to select to retrieve the student id because this value is being passed by variable $alunoId. Should stay like this: $sql = mysql_query("INSERT INTO fotosTeste VALUES('', '".$nome_imagem."', '".$alunoId."')");

  • Just below // Recupera os dados dos campos you will insert $alunoId = $_POST["alunoIDjS"]; and continues with its code.

  • vc will only change your javascrip on your page where you have HTML. Use the javascript I sent you. Don’t forget to link to jquery. Use the following CDN address <script src="https://code.jquery.com/jquery-2.2.3.min.js" integrity="sha256-a23g1Nt4dtEYOj7bR+vTu7+T8VP13humZFBJNIYoEJo=" crossorigin="anonymous"></script>

0

Loop (select in the student table) within this loop creates the INSERT INTO photos (id, image, id_student) VALUES (id, image, id_student)

Ai in SELECT to see the photos you can give an INNER JOIN on photos (photos.id_student = students.id)

  • hello rafael, you could show me in PHP syntax, if it’s not too much trouble. It’s not comfort, it’s because I’ve been racking my brain for a while and my last option was to ask someone.

Browser other questions tagged

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