Use ID generated from one FORM in another and UPDATE in bd

Asked

Viewed 274 times

1

inserir a descrição da imagem aqui

I recorded this image in the database generated me the ID:20.

Form to save : INICIAL.PHP (Code to save image)

<html>
<head>
    <title></title>
</head>
<body>
    <form enctype="multipart/form-data" method="post">
        <input type="file" name="image" /><br /> 
        <input type="submit" value="Enviar" name="sumit" />
    </form>
    <?php

    if(isset($_POST['sumit']))
    {
        if(getimagesize($_FILES['image']['tmp_name'])== FALSE)
        {
            echo "Selecione uma imagem.";
        }
        else
        {
            $image = addslashes($_FILES['image']['tmp_name']);
            $name = addslashes($_FILES['image']['name']);
            $image = file_get_contents($image);
            $image = base64_encode($image);
            saveimagem($name, $image);
        }
    }
    mostrarimagem();
    function saveimagem($name, $image)
    {

        $host = "localhost";
        $user = "root";
        $pass = "";
        $conexao = mysqli_connect($host, $user, $pass) or die (mysql_error());
        mysqli_select_db($conexao, "teste");
        $sql = "insert into cadastro (foto)  values ('$image')";
        $result = mysqli_query($conexao, $sql);
        if($result)
        {
            echo "<br/>Foi feito o upload" ;
            $id = mysqli_insert_id($conexao);
            echo $id;
        }else
        {
            echo "<br/>Não foi feito o upload";
        }
    }
    function mostrarimagem()
    {
        $host = "localhost";
        $user = "root";
        $pass = "";
        $conexao = mysqli_connect($host, $user, $pass) or die (mysql_error());
        mysqli_select_db($conexao, "teste");
        $sql = "select * from cadastro";
        $result = mysqli_query($conexao, $sql);

        while($row = mysqli_fetch_array($result))
        {
            echo '<img height="300" width="300" src="data:image;base64,'.$row[11].'">';
        }
        mysqli_close($conexao);
    }

    ?>
</body>

Where has the $id = mysqli_insert_id($conexao); is the variable that stored the last record in the database. I need to use it for the update in another form.

WRITE.PHP

<?php
//Irá receber os valores enviados e guardar no banco de dados

<?php
//Irá receber os valores enviados e guardar no banco de dados
if($_POST['enviar']){
    include 'inicial.php';
    $nome = $_POST['NomeAluno'];
    $dataNasc = $_POST['DataNasc'];
    $sexo = $_POST['Sexo'];
    $numcel = $_POST['Celular'];
    $numtel = $_POST['Telefone'];
    $endereco = $_POST['Endereco'];
    $numres = $_POST['NumResid'];
    $uf = $_POST['UF'];
    $rg = $_POST['RG'];
    $prontuario = $_POST['Prontuario'];
    $datavalidade = $_POST['DataValidade'];
    $curso = $_POST['Curso'];
    $semestre = $_POST['Semestre'];
    $periodo = $_POST['Periodo'];
    $email = $_POST['Email'];
    $senha = $_POST['Senha'];

    //"$sql = "SELECT MAX(ID) FROM cadastro";

    // Insere os dados no banco
    $sql = mysqli_query($conexao, "UPDATE cadastro set
                                        nome_aluno = ':$nome',
                                        data_nascimento = ':$dataNasc',
                                        sexo = ':$sexo', 
                                        celular = ':$numcel',
                                        telefone = ':$numtel',
                                        endereco = ':$endereco',
                                        numero = ':$numres',
                                        uf = ':$uf',
                                        rg = ':$rg',
                                        prontuario = ':$prontuario',
                                        data_validade = ':$datavalidade',
                                        curso = ':$curso',
                                        semestre = ':$semestre',
                                        periodo = ':$periodo',
                                        email = ':$email',
                                        senha = ':$senha'
                                  where id = '$id'");

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

I can’t update the table with the other values, without touching the photo that has already been saved. And using the $id variable, I even put the include 'inicial.php';.

I don’t know if it is my Update SQL that is wrong, but when I click save button this error appears: P Notice: Undefined variable: id in C:\wamp\www\ifsp\gravar.php on line 45

  • 1

    Those : in front of the variables is what?

  • 1

    I don’t know why I put it, but it didn’t change anything

  • Where you make the call from saveimage()? missing to return the $id in this function ;). takes these out : of everything.

  • I just put the include initial.php, with it will not everything that is on the page? I already took

  • Yes, but you need to call saveimage() pass the values and place at the end of the function return $id;

  • What values? So: include 'inicial.php'&#xA;saveimagem($id){&#xA; return $id&#xA; } . Of error yet Parse error: syntax error, unexpected '{' in C:\wamp\www\ifsp\gravar.php on line 22, something I noticed too, that when I click save in the form it redirects me to the page inicial.php, only because of include

  • in initial.php has more code than the function?

  • Got it, I’ll put it all up there

  • Dude, you have to see if the other fields accept null, because I realized you add the photo first and then you want to get the generated id to update the data right, you have to see tbm if the id is generated automatically.

  • Yes ID is auto_increment and when the photo is saved the fields are to accept null. : s

  • Has been answered then!

  • Similar: http://answall.com/questions/89986/pega-o-id-da-%C3%Baltima-line-in-database

  • @Edilson, no guy are not similar. This first didn’t even know how to get the ID. Now I don’t know use it

  • It’s basically the same thing. And another thing, even though you showed me what the problem is, it would help more if you said what you really want, or what you want the whole script to do.

  • Sorry. I’m not used to this forum yet. : x

Show 10 more comments

2 answers

0

First make the function return the id inserted with a return $id.

function saveimagem($name, $image) {

//codigo omitido

   if($result){
      echo "<br/>Foi feito o upload" ;
      $id = mysqli_insert_id($conexao);
      echo $id;
      return $id;   //<--- linha adicionada
   }else{
      echo "<br/>Não foi feito o upload";
   }
   return false;
}

Then in write.php take the id of saveimagem() with an assignment, then pass the variable in update

write php.

else {
    $image = addslashes($_FILES['image']['tmp_name']);
    $name = addslashes($_FILES['image']['name']);
    $image = file_get_contents($image);
    $image = base64_encode($image);
    $id_imagem = saveimagem($name, $image); //<--- linha nova atribuição
}

Dai lá non update, pass $id_imagem.

where id = $id_imagem");
  • I don’t understand what you mean by "get the ID of saveimagem() with an assignment. It would be something like? I don’t understand almost anything about this Function. If I can help with that '-'

0

Look do the following, let’s make your code simpler!

Create a new file

It can be called a connection

php connection.

    $host = "localhost";
    $user = "root";
    $pass = "";
    $conexao = mysqli_connect($host, $user, $pass) or die (mysql_error());
  //Conectar

Inicial.PHP

 <?php session_start(); ?>
<html>
 <head>
    <title></title>
 </head>
 <body>
    <form enctype="multipart/form-data" method="post">
        <input type="file" name="image" /><br /> 
        <input type="submit" value="Enviar" name="sumit" />
    </form>
    <?php

    if(isset($_POST['sumit']))
    {
        if(getimagesize($_FILES['image']['tmp_name'])== FALSE)
        {
            echo "Selecione uma imagem.";
        }
        else
        {
            $image = addslashes($_FILES['image']['tmp_name']);
            $name = addslashes($_FILES['image']['name']);
            $image = file_get_contents($image);
            $image = base64_encode($image);
            include_once 'conexao.php';
            saveimagem($name, $image);
        }
    }

    mostrarimagem();

    function saveimagem($name, $image)
    {
        mysqli_select_db($conexao, "teste");
        $sql = "insert into cadastro (foto)  values ('$image')";
        $result = mysqli_query($conexao, $sql);
        if($result)
        {
            echo "<br/>Foi feito o upload" ;
            $_SESSION['id_temp'] = mysqli_insert_id($conexao);
            echo $id;
        }else
        {
            echo "<br/>Não foi feito o upload";
        }
    }

    function mostrarimagem()
    {
        mysqli_select_db($conexao, "teste");
        $sql = "select * from cadastro";
        $result = mysqli_query($conexao, $sql);

        while($row = mysqli_fetch_array($result))
        {
            echo '<img height="300" width="300" src="data:image;base64,'.$row[11].'">';
        }
        mysqli_close($conexao);
    }

    ?>
</body>
</html>

Write.php

<?php
session_start();
//Irá receber os valores enviados e guardar no banco de dados
if($_POST['enviar']){
    include_once 'conexao.php';
    $nome = $_POST['NomeAluno'];
    $dataNasc = $_POST['DataNasc'];
    $sexo = $_POST['Sexo'];
    $numcel = $_POST['Celular'];
    $numtel = $_POST['Telefone'];
    $endereco = $_POST['Endereco'];
    $numres = $_POST['NumResid'];
    $uf = $_POST['UF'];
    $rg = $_POST['RG'];
    $prontuario = $_POST['Prontuario'];
    $datavalidade = $_POST['DataValidade'];
    $curso = $_POST['Curso'];
    $semestre = $_POST['Semestre'];
    $periodo = $_POST['Periodo'];
    $email = $_POST['Email'];
    $senha = $_POST['Senha'];

    // Insere os dados no banco
    $sql = mysqli_query($conexao, "UPDATE cadastro set
                                        nome_aluno = '$nome',
                                        data_nascimento = '$dataNasc',
                                        sexo = '$sexo', 
                                        celular = '$numcel',
                                        telefone = '$numtel',
                                        endereco = '$endereco',
                                        numero = '$numres',
                                        uf = '$uf',
                                        rg = '$rg',
                                        prontuario = '$prontuario',
                                        data_validade = '$datavalidade',
                                        curso = '$curso',
                                        semestre = '$semestre',
                                        periodo = '$periodo',
                                        email = '$email',
                                        senha = '$senha'
                                  where id =".$_SESSION['id_temp']);

    // Se os dados forem inseridos com sucesso
    if ($sql){
        echo "Você foi cadastrado com sucesso.";
        if(isset($_SESSION['id_temp'])){
            unset($_SESSION['id_temp']);
        }else{
            echo "<script>alert('ocorreu um erro, pois a session para o id não foi criada')</script>";
        }
    }
  • That I managed to do with $id = mysqli_insert_id($conexao); , I am unable to update where I have the last ID saved

  • Saved in a session! $_SESSION['id_temp'] = mysqli_insert_id($connected); - Then only put in query and delete Session!

  • I did that, then in the query I put: where id = 'id_temp'");, no error appeared but also did not update the database

  • No brother, you have to put it like this: WHERE id = '$_SESSION['id_temp']'"); - Ai after you use it to clear the session, unset($_SESSION['id_temp']);

  • Ah yes, I made the change now gave this mistake: Parse error: syntax error, unexpected '' (T_ENCAPSED_AND_WHITESPACE), expecting identifier (T_STRING) or variable (T_VARIABLE) or number (T_NUM_STRING) in C:\wamp\www\ifsp\gravar.php on line 45

  • Look up and try again!

  • Did you get include 'initial.php' right? I put exactly how you sent me and gave the following errors: Notice: Undefined variable: _SESSION in C:\wamp\www\ifsp\gravar.php on line 55 and Notice: Undefined variable: _SESSION in C:\wamp\www\ifsp\gravar.php on line 60

  • Try now, if you are right, take the if(isset($_SESSION['id_temp']), because it serves to give an alert if you are not generating the Session

  • I changed all, including the connection. But still returned an error: Notice: Undefined variable: _SESSION in C:\wamp\www\ifsp\gravar.php on line 40 . In the database without changes (update), D:

  • Is it not something in the database?

  • You are using javascript ajax or load()?

  • Where is this? The only place I used Javascript was in the form for field validation, check if it is not empty. Already these "Functions etc" just followed a tutorial on the internet how to use them

  • Putz cara que merda, I forgot session_start(); - Put this command at the beginning of the initial file and save file!

  • I had thought about it up. I put the two Septssion now it changed the error to: Notice: Undefined index: id_temp in C:\wamp\www\ifsp\gravar.php on line 41. It’s hard. I really appreciate your patience, man

  • tried to put session_start only at the initial?

  • Yes. Hence he gives this mistake: Notice: Undefined variable: _SESSION in C:\wamp\www\ifsp\gravar.php on line 41 :/

Show 11 more comments

Browser other questions tagged

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