Registering form in the Database

Asked

Viewed 43 times

0

  <body>
        <?php
        $titulo = $_POST['titulo2'];
        $cap = $_POST['capitulo2'];
        $opt = $_POST['opcoes'];


        $conexao = mysqli_connect("localhost","root","","report");
        $sql2 = "insert into avise values(null,'".$titulo."','".$cap."','".$opt."')";



        if(mysqli_query($conexao, $sql2)) {

            $msg = "Enviado! Obrigado pelo feedback.";
        } else {
            $msg = "Erro ao enviar!";
        }
        mysqli_close($conexao);

        ?>

        <script> alert('<?php echo $msg;?>');
            location.href="index.php";
            </script>
    </body>

Hello! I recently stopped by and they helped me to send notices by email. Now I’m wanting to send these notices to the database. But he’s not registering.

body {
    margin: 0;
    font-family: "Tahoma";
}

.reporte {
    background-color: #ffffff;
    width: 400px;
    text-align: center;
    border-radius: 10px;
    position: fixed;
    z-index: 10001;
    top: 50%;
    left: 50%;
    margin-left: -230px;
    margin-top: -150px;
    display: none;
}

.campo h2 {
    display: inline-block;
    color: #a42f2f;
}

.campo p {
    margin-top: 0;
    color: #127d2b;
    display: none;
}

select, input {
    margin-bottom: 10px;
    outline: 0;
}

label {
    font-size: 14px;
    color: #888888;
}

select, input {
    border: none;
    background-color: #e2e2e2;
    padding: 5px 10px;
    border-radius: 5px;
}

select {
    color: #888888;
}

#btn {
    background-color: #ffffff;
    border: 2px solid #a42f2f;
    color: #a42f2f;
    padding: 6px 15px;
    cursor: pointer;
    margin-bottom: 10px;
}

#btn:hover {
    background-color: #a42f2f;
    color: #ffffff;
}

#opacidade {
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.6);
    position: fixed;
    z-index: 10000;
    display: none;
}

.teste a {
background-color: #ffffff;
border: 1px solid #a42f2f;;
color: #a42f2f;

}
<body>
<div class="teste">
  <a href="#">Enviar</a>
</div>
    <div class="reporte">
        <div class="campo">

            <h2>Informe o Erro</h2>
            <p class="feedback">Enviado! Obrigado pelo feedback.</p>
            <form action="gravar-aviso.php" method="post">

                <label for="titulo2">Digite o título:</label></br>
                <input type="text" name="titulo2" id="titulo2" placeholder="Naruto..." required></br>

                <label for="capitulo2">Digite o número:</label></br>
                <input type="text" name="capitulo2" id="capitulo2" placeholder="01..." required></br>
                <input type="submit" value="Enviar" id="btn">
            </form>

        </div>
    </div>
    <div id="opacidade"></div>
</body>

<!-- begin snippet: js hide: false console: true babel: false -->

  • Then Francisco the name of the bank is report with the table warn. The friend below helped but it was mt drawn up. I wanted to use my method only find the error. I am trying to send but not register.

  • Does not return error and does not send data only gives the message I put on Else $msg = "Error while writing!";

  • In the database I created this: create database report; use report; create table warn( Cod int Primary key auto_increment, varchar(50), varchar(50), error Enum('No pages', 'Repeated Chapter', 'Shuffled Pages', 'Missing Page', 'Repeated Pages') );

  • Returned this error: http://prntscr.com/fuzef5

  • You changed the name of the connection variable?

  • N. $con = mysqli_connect("localhost","root"","");

  • Changed, in the example of the question you used the name $conexao and now it’s $con, so do: $msg = mysqli_error($con);

  • Ahh yes. I switched... did agr here, showed no error. Only a blank page.

  • Before I had my alert saying only Error when sending. Agr when you asked to do this command, it is on a blank screen. And no longer appears nd.

Show 4 more comments

3 answers

0

Create a connection file:

class Connection
{
    private $localhost;
    private $username;
    private $password;
    private $database;

    public function __construct()
    {
        $this->username = 'root';
        $this->password = '';
        $this->database = 'report';
        $this->localhost = 'localhost';
    }

    public function getInstance()
    {
        return new mysqli($this->localhost, $this->username, $this->password, $this->database);
    }

}

You can do something like this:

<?php
class Avise
{
    private $titulo;
    private $capitulo;
    private $opcoes;
    private $query;

    public function __construct($request)
    {
       $conn = new Connection();
       $this->query = $conn->getInstance();

       $this->titulo = isset($request['titulo2']) ? $request['titulo2'] : "";
       $this->capitulo = isset($request['capitulo2']) ? (int) $request['capitulo2'] : "";
       $this->opcoes = isset($request['opcoes'])  ? $request['opcoes'] : "";
    }

    public function cadastrar()
    {

        try {
            $stmt = $this->query->prepare("INSERT INTO avise VALUES(?, ?, ?)");

            if ($this->titulo == "") {
                throw new Exception('Título não deve ser vazio.');
            }

            if ($this->capitulo == "") {
                throw new Exception('O capítulo não pode ser vazio.');
            }

            if ($this->opcoes == "") {
                throw new Exception('Opções não pode ser vazio.');
            }

            if (!$stmt->bind_param('sis', $this->titulo, $this->capitulo, $this->opcoes)) {
                throw new Exception('Número de parâmetros incorreto! Erro: '. $stmt->error);
            }

            if (!$stmt->execute()) {
               throw new Exception('Erro de execução! Erro: '. $stmt->error);
            }

            return array(
               'message' => 'Enviado! Obrigado pelo feedback.',
               'status' => true
            );

        } catch (Exception $e) {
            return array(
              'message' => $e->getMessage(),
              'status' => false
            );
        }
    }
}
//usando a classe Avise...

$mensagem_erro = null;
$mensagem_sucesso = null;
    if ($_POST) {
       $avise = new Avise($_POST);
       $result = $avise->cadastrar();
       if ($result['status']) {
           //gravou normal
          $mensagem_sucesso = $result['message'];
       } else {
          //mensagem de erro
          $mensagem_erro = $result['message'];
       }
    }
    ?>
    <body>
    <div class="teste">
      <a href="#">Enviar</a>
    </div>
        <div class="reporte">
            <div class="campo"> <?php
           if ($mensagem_erro != null) {
                echo '<h2>Informe o Erro</h2>
                   <p class="feedback">'.$mensagem_erro.'</p>';
           }

           if ($mensagem_sucesso != null) {
               echo '<h2>Informe o Sucesso</h2>
                   <p class="feedback">'.$mensagem_sucesso.'</p>';
           }
           ?>
                <form action="<?php echo $_SERVER['SCRIPT_NAME'];?>" method="post">

                    <label for="titulo2">Digite o título:</label></br>
                    <input type="text" name="titulo2" id="titulo2" placeholder="Naruto..." required></br>

                    <label for="capitulo2">Digite o número:</label></br>
                    <input type="text" name="capitulo2" id="capitulo2" placeholder="01..." required></br>
                    <input type="hidden" name="opcoes" value="blablabla" id="opcoes">
                    <input type="submit" value="Enviar" id="btn">
                </form>

            </div>
        </div>
        <div id="opacidade"></div>
    </body>

0

Instead of using the null, to use a predefined value (auto_increment), use the default.

And from what you told me, your table is made that way:

cod int primary key auto_increment,
manga varchar(50),
capitulo varchar(50),

Totaling 3 columns, you are trying to insert 4 parameters.

Try it this way:

$sql2 = "INSERT INTO avise VALUES(default,'$titulo','$cap')";
  • However, the error column that would be a select: error Enum('No pages','Repeated chapter', 'Shuffled pages', 'Missing page', 'Repeated pages')

  • Solved. I took One from the part where would be the select. Mt thank you.

  • I believe you were using Enum a little wrong, see this.

  • From what you’re saying, it seems to be the case mark an answer as accepted. Here we do not write "solved" in the question. If you have an answer that really helped you, mark it as accepted. If you came to the solution on your own, put in the solution as an answer. So content is more organized and easier to find in the future by other people with similar problems.

  • Ready. But I have an agr error in the bank: The accents are with the messy characters.

  • @Oliverdamon Ai is quite different from the scope of the question. This is a character type error, you should put it in UTF-8.

Show 1 more comment

0

Solved. I changed the settings in the database.

//o banco de dados estava:

erro enum('Sem páginas','Capítulo repetido', 'Páginas embaralhadas', 'Falta página', 'Páginas repetidas')

//mudei para: 

erro varchar(50)

  • You used the answer area to add clarifications or ask a question. Instead, it is better to include this content in the question itself. To do this, just click on the [Edit] link, which is just below the question. Thus, the content is all gathered in one place, and those who arrive here need not be looking for information in various responses and comments to understand the problem.

Browser other questions tagged

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