Sending only the id

Asked

Viewed 69 times

-2

I have the following form

</p>
  <p align="center">Nome:
    <input name="nome" type="text" id="nome">
    <br />
    <br />
    <strong>Email:</strong> 
    <input name="email" type="text" id="email" size="45" />
    <br />
    <br />
    <strong>Palpites Grupo A <span class="style1">PRIMEIRA</span> Rodada dias 14/06 e 15/06</strong><br />
    <textarea name="palpites" id="palpites" cols="45" rows="2">A X - X B
C X - X D
      </textarea>
    <br />
    <br />
    <strong>Palpites Grupo A <span class="style1">SEGUNDA</span> Rodada dias 19/06 e 20/06</strong><br />
      <textarea name="palpites2" id="palpites2" cols="45" rows="2">A X - X C
B X - X D
      </textarea>
    <br />
    <br />
    <strong>Palpites Grupo A <span class="style1">TERCEIRA</span> Rodada dia 25/06</strong><br />
      <textarea name="palpites3" id="palpites3" cols="45" rows="2">A X - X D
B X - X C
      </textarea>
    <br />
    <br />

    <input type="submit" value="Cadastrar" >
    </p>
</form>
</body>
</html>

and my page register this as follows

<?php

$connect = mysql_connect('localhost','root','');
$db = mysql_select_db('copa');
$query = "INSERT INTO palpites (id,nome,email,palpites,palpites2,palpites3) VALUES ('$id','$nome','$email','$palpites','$palpites2','$palpites3')"; 
@mysql_query($query);
@mysql_close();//fecha conexao


?>


<script>

alert("dados gravados com sucesso") ;

</script>

// volta pra lá

<?PHP

header("Refresh: 0; /bolao/home/palpitar.php");

?>

But only the id is being sent, or actually being placed automatically by mysql, can anyone please help me? Att Alberico

  • You have defined the variables $nome, $email, etc, which use to create the record? In the code you posted they are not defined.

  • It would be nice to boot that lot of @ in your code. On rare occasions this is good. And in all of them where you’re good, you have complete control of what you’re doing. Another thing that you don’t normally have in well-made code is JS Alert via PHP, and surely your header refresh is not an easy solution to debug (it probably has many better ways to do what you want without improvisations of this nature).

  • Anderson good afternoon, I do not have much knowledge, how so defined ? Because in the database I created the same way.

  • The HTML code is incomplete, which method you are using in the form, GET or POST?

  • Have you thought about using codeigniter is very useful and will help you a lot

  • If any answer solved your problem mark it as accepted, see how and why in https://pt.meta.stackoverflow.com/questions/1078/como-e-por-que-aceitar-uma-resposta/1079#1079

Show 1 more comment

2 answers

1

1º MYSQL

Mysql functions had become obsolete after updates. Mysqli is currently used for its superior performance and some advantages. Read about this link: https://secure.php.net/manual/en/book.mysqli.php

2º CONNECTION TO THE DATABASE

As a way to ensure more security and better handling with DB, a separate page should be made for the connection as follows.

1 - Create a php page called connected.php. After creating, add your connection on this page. Thus remaining:

<?php
$servidor = "localhost";
$usuario = "root";
$senha = "";
$dbname = "copa";

//Criar a conexao
$conn = mysqli_connect($servidor, $usuario, $senha, $dbname);

if(!$conn){
    die("Falha na conexao: " . mysqli_connect_error());
}       
?>

Thus avoiding duplicate connections. Save your connection where you wish (Preferably in the root folder along with the pages to follow this tutorial correctly).

3rd FORM

You should first have the form send your data to PHP.

at the beginning of the tag , assigns it as POST method.

<form  enctype="multipart/form-data" name="form" method="POST">

After assigning, add a name to your button:

<input type="submit" value="Cadastrar" name="btnForm">

So you can call the dice when the button is triggered.

Save your form where you wish (Preferably in the root folder along with the pages to follow this tutorial correctly).

4th ENTERING DATA

You need to transfer your form input values into the INSERT.

This way:

<?php
include_once("conexao.php"); // Incluir sua conexão com o banco de dados.
include_once("formulario.php"); // Incluir a página do seu formulário.
$btnForm = filter_input(INPUT_POST, 'btnForm', FILTER_SANITIZE_STRING);

if($btnForm){
 include_once 'conexao.php';
 $dados = filter_input_array(INPUT_POST, FILTER_DEFAULT);

 $inserirBD = "INSERT INTO palpites (nome, email, palpites, palpites2, palpites3) VALUES (
                '" .$dados['nome']. "',
                '" .$dados['email']. "',
                '" .$dados['palpites']. "',
                '" .$dados['palpites2']. "',
                '" .$dados['palpites3']. "'
                )";


$resultado = mysqli_query($conn, $inserirBD);
if(mysqli_insert_id($conn)){
    echo "
        <META HTTP-EQUIV=REFRESH CONTENT = '0;URL=http://localhost/PASTA/formulario.php'>
        <script type=\"text/javascript\">
        alert(\"Dados inseridos com sucesso.\");
        </script>
        "; // Cria um alerta para seu cadastro.
}else{
    echo "
        <META HTTP-EQUIV=REFRESH CONTENT = '0;URL=http://localhost/PASTA/formulario.php'>
        <script type=\"text/javascript\">
        alert(\"Erro ao inserir dados.\");
        </script>
        "; // Cria um alerta para seu cadastro.
}   

}       
?>

Remembering that when you create an id in Mysql, you can put it to be AUTO INCREMENT, where it goes counting every time you add a new guess, all automatic, not needing to add it in Mysql INSERT.

  • Actually I took an example of an application of mine, where I forgot to delete rsrs

1

I’m not sticking to the form because I think you only posted part of it.

Mysql functions are obsolete, removed from PHP 7. Use mysqli or PDO.

1 - Example in mysqli.

<?php
if(isset($_POST["submit"])) {

    $connect = mysqli_connect("localhost", "root", "", "copa");

    // Verifique a conexão
    if($connect === false){
        die("ERRO: não foi possível conectar. " . mysqli_connect_error());
    }
    //DEFININDO AS VARIAVEIS
    //Para evitar injeção, a Solução Ideal seria: Prepared Statements,
    // mas para não dificultar seu aprendizado  utilizarei mysqli_real_escape_string
   //que serve para escapar os caracteres especiais e evitar em partes a injeção

   $nome = mysqli_real_escape_string($connect, $_REQUEST['nome']);
   $email = mysqli_real_escape_string($connect, $_REQUEST['email']);
   $palpites = mysqli_real_escape_string($connect, $_REQUEST['palpites']);
   $palpites2 = mysqli_real_escape_string($connect, $_REQUEST['palpites2']);
   $palpites3 = mysqli_real_escape_string($connect, $_REQUEST['palpites3']);

   $query = "INSERT INTO palpites (nome, email, palpites, palpites2, palpites3) VALUES ('$nome', '$email', '$palpites', '$palpites2', '$palpites3')";
   if(mysqli_query($connect, $query)){
       //echo "Registros adicionados com sucesso.";
       // ou
       //alert, redirecionamento, etccc
   } else{
       //echo "ERRO: não foi possível executar $query. " . mysqli_error($connect);
       // ou
       //alert, etccc
   }

   // fecha conexão
   mysqli_close($connect);

}
?>

id is not needed in the query depending on your comment ou na verdade sendo colocado de forma automatica

2 - Example in PDO.

<?php
if(isset($_POST["submit"])) {
 try{
    $pdo = new PDO("mysql:host=localhost;dbname=copa", "root", "");
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
 } catch(PDOException $e){
    die("ERRO: não foi possível conectar. " . $e->getMessage());
 }

 try{
    // prepared statement
    $sql = "INSERT INTO palpites (nome, email, palpites, palpites2, palpites3) VALUES (:nome, :email, :palpites, :palpites2, :palpites3)";
    $stmt = $pdo->prepare($sql);


    $stmt->bindParam(':nome', $_REQUEST['nome']);
    $stmt->bindParam(':email', $_REQUEST['email']);
    $stmt->bindParam(':palpites', $_REQUEST['palpites']);
    $stmt->bindParam(':palpites2', $_REQUEST['palpites2']);
    $stmt->bindParam(':palpites3', $_REQUEST['palpites3']);

    $stmt->execute();
    echo "Registros adicionados com sucesso.";
    // ou
    //alert, redirecionamento, etccc
 } catch(PDOException $e){
    die("ERRO: não foi possível executar $sql. " . $e->getMessage());
    // ou
    //alert, etccc
 }

 // fecha conexão
 unset($pdo);

}
?>

Prepared statements provide strong protection against SQL injection, because parameter values are not directly embedded within the SQL query string.

Browser other questions tagged

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