error when registering in the bank

Asked

Viewed 160 times

0

The following error message is appearing:

Notice: Undefined index: razao_social in C:\xampp2\htdocs\estudo\cadastroPrestador.php on line 5

Notice: Undefined index: nome_fantasia in C:\xampp2\htdocs\estudo\cadastroPrestador.php on line 6

Warning: mysqli_query() expects at least 2 parameters, 1 given in C:\xampp2\htdocs\estudo\cadastroPrestador.php on line 12
erro ao tentar cadastrar

connects.php:

<?php
    $servidor='localhost';
    $usuario='root';
    $senha='';
    $bancodedados='cis';


    $strcon = mysqli_connect($servidor,$usuario,$senha,$bancodedados);
?>

cadastre.php:

    <?php
    include_once("conecta.php");



    $idPrest = $_POST['id'];
    $razaoSoc = $_POST['razao_social'];
    $NomeFanta = $_POST['nome_fantasia'];
    $NumCnpj = $_POST['CNPJ'];
    $Tip = ['tipo'];


    $sql = "INSERT INTO cadastroprestador(ID_PREST,Razão_Social,Nome_Fantasia,CNPJ) VALUES ('$idPrest', '$razaoSoc', '$NomeFanta', '$NumCnpj')";
    mysqli_query($sql) or die ("erro ao tentar cadastrar");
    mysql_close($strcon);
    echo "Cadastrado Com sucesso";
?>
<html>
<head>
<title>Cadastro Prestador</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- Bootstrap -->
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<!-- Latest compiled JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>

<body>
<!-- menu -->

<nav class="navbar navbar-inverse">
  <div class="container-inverse">
        <div class="navbar-header">
            <a class="navbar-brand" href="#">Cadastro de Prestador</a>
        </div>

  </div>
 </nav>
<div class="container">
<div class="panel panel-primary">
      <div class="panel-heading">Prestador</div>
      <div class="panel-body">
        <form name "Ficha1" action="cadastroprestador.php" method="POST">
            <div class="form-group" id="Prestador">
                <div class="col-lg-2">
                <label for="ex1">ID</label>
                <input class="form-control" name="id" type="text" >
            </div>
            <div class="col-lg-12 form-group">
                <label for="ex2">Razão Social</label>
                    <input class="form-control" name="razao_social" type="text">
            </div>
            <div class="col-lg-6 form-group">
                <label for="ex3">Nome Fantasia</label>
                    <input class="form-control" name="nome_fantasia" type="text">
            </div>
            <div class="col-lg-6 form-group">
                <label for="ex4">CNPJ</label>
                    <input class="form-control" name="CNPJ" type="text">
            </div>      
            <div class="col-lg-6 form-group">
                <label for="ex6">Tipo</label>
                    <select class="form-control" name="tipo">
                            <option>HOSPITAL</option>
                            <option>CLINICA</option>
                            <option>LABORATORIO</option>
                            <option>REMOÇÃO</option>
                            </select>
            </div>  
            <div class="col-lg-6 form-group">
                <label for="ex5">Indicação</label>
                    <select class="form-control" name="indicacao">
                        <option>Prospecção</option>
                        <option></option>
                        <option></option>
                        <option></option>
                        </select>
            </div>
            <button type="submit" class="btn btn-primary col-lg-2 right" id="btn_cad">Cadastro</button>      

        </form> 
      </div>
    </div>
</div>
</body>
</html>
  • 1

    Solution: https://answall.com/questions/21714/como-resolver-um-notice-undefined-index

  • In the case of your code, the interesting thing would be to insert the isset as it explains in the topic I put the link. The "type" field assignment is without the $.post in the PHP file.

  • Whenever an answer solves your problem mark it as accepted. See how in https://i.stack.Imgur.com/jx7Ts.png and why in https://pt.meta.stackoverflow.com/questions/1078/como-e-por-que-aceitar-uma-resposta/1079#1079

  • Enjoy a tour https://answall.com/tour

2 answers

1


Errors in your script

Is not mysqli_query($sql) and yes mysqli_query($strcon,$sql)

Is not mysql_close($strcon); and yes mysqli_close($strcon);

The $_POST variables as you well know receive the data passed by an HTTP POST request. Probably these variables have not been passed yet in the request and therefore do not exist. No use calling something that does not exist.

Solution

Validate the client side and the server side. This will prevent the error Notice: Undefined index and avoid an INSERT without values.

  • Client-side: The attribute required.

    This is a Boolean attribute used to indicate that a determining form field is mandatory for sending the form. When adding this attribute to a form field, the browser forces the user to enter data in that field before submitting the form.

    This validation replaces the basic form validation implemented with Javascript, making things a little more useful and saving us some development time

    Examples:

    <input class="form-control required" name="id" type="text" required>

    <select class="form-control" name="tipo" required>

  • Server-side

    // Cria uma variável que terá os dados do erro
    $erro = false;
    
    // Verifica se o POST tem algum valor
    if ( !isset( $_POST ) || empty( $_POST ) ) {
        $erro = 'Nada foi postado.';
    }
    
    // Cria as variáveis dinamicamente
    foreach ( $_POST as $chave => $valor ) {
        // Remove todas as tags HTML
        // Remove os espaços em branco do valor
        $valor=trim($valor);
        $$chave = trim( strip_tags( $valor ) );
    
        // Verifica se tem algum valor nulo
        if ( empty ( $valor ) || $valor=="" ) {
            $erro = 'Existem campos em branco.';
        }
    }
    
    // Se existir algum erro, mostra o erro
    if ( $erro ) {
        echo $erro;
    } else {
        // Se a variável erro continuar com valor falso
        // Faça o INSERT aqui
    
            include_once("conecta.php");
    
            $idPrest = $_POST['id'];
            $razaoSoc = $_POST['razao_social'];
            $NomeFanta = $_POST['nome_fantasia'];
            $NumCnpj = $_POST['CNPJ'];
            $Tip = ['tipo'];
    
            $sql = "INSERT INTO cadastroprestador(ID_PREST,Razão_Social,Nome_Fantasia,CNPJ) VALUES ('$idPrest', '$razaoSoc', '$NomeFanta', '$NumCnpj')";
            mysqli_query($strcon,$sql) or die ("erro ao tentar cadastrar");
    
            echo "Cadastrado Com sucesso";
            mysqli_close($strcon);
    
     } 
    

Why client-side (Front-end) and server-side validation (Back-end)?

Validating data being sent by the user only in javascript is not enough because of:

  • If the user disables javascript, you may end up with invalid data on the server

  • Because the front end is accessible in the browser. And every code there could end up being altered by someone with advanced knowledge and bad intentions. The Javascript code can be perfectly changed and so the validation can be circumvented.

  • server validations make a site less susceptible to malicious robots

In short... it is worth taking precautions against all these unknown agents, making the validation on the server (which is the most trusted agent) the main one... and in javascript, as a validation agilizer, because it does not need to go on the server.

  • Leo, I tried to put your code both at the beginning and at the end, it’s still giving error <? php if (isset($_POST['send']){ include_once("connects.php"); echo "Successfully Registered"; $idPrest = $_POST['id']; $razaoSoc = $_POST['razao_social']; $Namesake = $_POST['name_fantasy']; $Numcnpj = $_POST['CNPJ'];&#xA;$Tip = ['tipo'];&#xA;&#xA;&#xA;$sql = "INSERT INTO cadastroprestador(ID_PREST,Razão_Social,Nome_Fantasia,CNPJ) VALUES ('$idPrest', '$razaoSoc', '$NomeFanta', '$NumCnpj')";&#xA;mysqli_query($sql) or die ("erro ao tentar cadastrar");&#xA;mysql_close($strcon);&#xA;&#xA;&#xA;?>

  • Parse error: syntax error, Unexpected '{' in C: xampp2 htdocs estudo cadastroPrestador.php on line 3

  • @MAGUIM lacked a closing parentesis if (isset($_POST['enviar'])){

  • @MAGUIM the way you did in the comment is wrong

  • I tried anyway this giving error, Notice: Undefined variable: strcon in C: xampp2 htdocs study cadastral.php on line 14 Warning: mysqli_query() expects Parameter 1 to be mysqli, null Given in C: xampp2 htdocs study cadastral.php on line 14 error when trying to register

  • @MAGUIM, strcon is the string of your connection. I hadn’t noticed, the correct is mysqli_query($strcon,$sql) or die ("erro ao tentar cadastrar");

  • opa, but agr seems this error here mysqli_query() expects Parameter 1 to be mysqli, null Given in line 14

  • obg by example however I had to make some changes, I was using outdated xampp and was using variables that he did not recognize, so I updated the shaman and I re-structured the obg code by the for and excuse my ignorance.

Show 3 more comments

0

Good guys I’ll leave with settled!

I had to make some bank changes, I was using an outdated Xampp that didn’t recognize the variables.

Another point was the way to structure the code, I had to make a beginner code to better understand the back-end.

This error was because I was forgetting to use the connection variable in the insertion query: ($strcon)

mysqli_query() expects parameter 1 to be mysqli, null given in line

and stayed like this:

$sql = mysqli_query($strcon, "INSERT INTO cadastroprestador(ID_PREST,Razao_Social,Nome_Fantasia,CNPJ) 
VALUES ('$idPrest', '$razaoSoc', '$NomeFanta', '$NumCnpj')");

follows how the code is structured:

<html>

<head>
<title>Cadastro...</title>
</head>
<?php
$servidor='localhost';
$usuario='root';
$senha='';
$bancodedados='cis';
$strcon = mysqli_connect($servidor,$usuario,$senha,$bancodedados) or die ("não conectado com banco")
?>

<?php
$idPrest = $_POST['id'];
$razaoSoc = $_POST['razao_social'];
$NomeFanta = $_POST['nome_fantasia'];
$NumCnpj = $_POST['CNPJ'];
$Tip = $_POST['tipo'];
$sql = mysqli_query($strcon, "INSERT INTO cadastroprestador(ID_PREST,Razao_Social,Nome_Fantasia,CNPJ) 
VALUES ('$idPrest', '$razaoSoc', '$NomeFanta', '$NumCnpj')");

echo "Cadastro com Sucesso"


?>

</html>

I wanted to thank everyone for their patience

Hugs

Browser other questions tagged

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