html form with PHP code to insert into mysql

Asked

Viewed 2,062 times

-1

I’m starting now with HTML, Mysql Phpe with Sublime using XAMPP.

I am making a test form in HTML to include directly in Mysql.

However it is not including the data.

I’ve done several tests, including the latter copied from the internet, and still does not include in the form.

Form code:

<!DOCTYPE html>
<html lang="pt-br">
<head>
  <meta charset="utf-8">
  <title> Testando conexão ao banco de dados </title>
</head>
<body>
  <h3>Formulário de Cadastro de Clientes</h3><br>
  <form name="Cadastro" action="cadastrar.php" method="POST">
    <label>Nome do Cliente: </label>
    <input type="text" name="NomeCliente" size="30"><br>
    <label>Sobrenome do Cliente: </label>
    <input type="text" name="SobrenomeCliente" size="45"><br>
    <label>Sexo do Cliente: </label>
    <select name="Sexo">
      <option value="M">Masculino</option>
      <option value="F">Feminino</option>
      <option value="N">Não Declarado</option>
    </select><br>
    <input type="submit" name="enviar" value="Enviar">
  </form>
</body>
</html>

PHP code connecting to the database:

<?php
$nome = $_POST['NomeCliente'];
$sobrenome = $_POST['SobrenomeCliente'];
$sexo = $_POST['Sexo'];
$strcon = mysqli_connect('localhost','root','','cadastro') or die('Erro ao conectar ao banco de dados');
$sql = "INSERT INTO banco_teste VALUES ";
$sql .= "('$nome', '$sobrenome', '$sexo')"; 
mysqli_query($strcon,$sql) or die("Erro ao tentar cadastrar registro");
mysqli_close($strcon);
echo "Cliente cadastrado com sucesso!";
echo "<a href='formulario.html'>Clique aqui para realizar um novo cadastro</a><br>";
echo "<a href='consulta.php'>Clique aqui para realizar uma consulta</a><br>";
?>

When I include data in the form this appears on the screen and does not insert the data in phpMyAdmin:

<?php
$nome = $_POST['NomeCliente'];
$sobrenome = $_POST['SobrenomeCliente'];
$sexo = $_POST['Sexo'];
$strcon = mysqli_connect('localhost','root','','cadastro') or die('Erro ao conectar ao banco de dados');
$sql = "INSERT INTO 'banco_teste' VALUES ";
$sql .= "('$nome', '$sobrenome', '$sexo')"; 
mysqli_query($strcon,$sql) or die("Erro ao tentar cadastrar registro");
mysqli_close($strcon);
echo "Cliente cadastrado com sucesso!";
echo "<a href='formulario.html'>Clique aqui para realizar um novo cadastro</a><br>";
echo "<a href='consulta.php'>Clique aqui para realizar uma consulta</a><br>";
?>
  • Do you see the php code when you open the page in your browser? How are you accessing the page? What is the address in your browser?

3 answers

2

The problem is that in your query you are not stating where the data will be entered.

How are you:

$sql = "INSERT INTO 'banco_teste' VALUES ";
$sql .= "('$nome', '$sobrenome', '$sexo')";

Properly:

$sql = "INSERT INTO 'banco_teste'(nome, sobrenome, sexo) VALUES ";
$sql .= "('$nome', '$sobrenome', '$sexo')"; 
  • 1

    It may be, but it is not mandatory to specify which columns the values should be entered in. If that’s the problem, the end result should be Erro ao tentar cadastrar registro which is what’s on die after trying to run the query.

  • @Milk of course is required, either you mention the names of the desa form fields, or use the SET, but you have to specify in which column the content will be inserted, unless the data is inserted in all columns.

  • 1

    This is already off-topic. I was just trying to help you. But, it’s not mandatory, you can do the test there. If it’s just those 3 columns that he has in the table, so you’ll need to specify?

  • As usual the id is defined as auto increment, is used in specific cases the Insert with this structure.

  • @Milk, as I said, it is not necessary to specify, when the Insert is performed in all columns of the table, in a common frame table, the id is defined as auto_increment because there is no way and need to do manual control.

  • 1

    You can set the ID to null and we don’t know the structure of his table. banco_teste has 4 fields yes, id, nome, sobrenome and sexo. The query would be INSERT INTO banco_teste VALUES (NULL, 'Onome', 'Osobrenome', 'Masculino')

  • But in this case you’re not defining how NULL :). Anyway, let’s close this subject because it’s escaping from the context of the topic.

  • Yes, it’s already off-topic. But! Null only causes the ID to be incremented if it is auto-increment clear-cut

Show 3 more comments

1

In the HTML form you must include an action, for example:

<form action="inserir.php">
<div class="form-group>
   <label for="nomeCliente">Nome do Cliente</label>
   <input type="text" id="nome" name="nome">
</div>
<button type="submit">Inserir</button>

On a page called insert.php you have to put the following code:

<?php
// LIGAR A BASE DE DADOS
$link = mysqli_connect("localhost", "user", "password", "nome_da_base_de_dados");

// VERIFICAR CONEXÃO
if($link === false){
    die("ERRO AO LIGAR À BASE DE DADOS. " . mysqli_connect_error());
}

// ESCAPE INPUTS
$nome = mysqli_real_escape_string($link, $_REQUEST['nome']);

// INSERIR DADOS NA TABELA
$sql = "INSERT INTO nome_da_tabela (name) VALUES ('$name')";

// VOLTAR A PAGINA DO FORMULARIO
if(mysqli_query($link, $sql)){
    mysqli_close($link);
    header('Location: ../pagina_do_formulario.php');
    exit;
} else {
    echo "Não foi possível adicionar o cliente.";
}
?>

I hope I’ve helped.

0

If when you submit the form, what appears to you is the PHP code you should be saving to the database, the way you should be accessing the page is wrong.

You’re using an address like http://localhost/omeuprojecto/ or file:///caminho/para/o/projecto/index.html?

If it’s the 2nd, you need to make sure you have the XAMPP started, and try to access it using http://localhost/.

If it doesn’t work, XAMPP can be in a different port, to see which port, you can open the XAMPP Control Panel and see here which port Apache is using, in principle it will be 80 and 443, if it is different from 80, for example 81, you’ll have to use http://localhost:81

Browser other questions tagged

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