When sending data via POST does not insert into the database

Asked

Viewed 89 times

-1

I have this form and script on one page:

<section class="hide-section" id="produto_1"> 
<form class="form-validate" id="feedback_form">
    <div class="campo">
        <fieldset> 
            <h1>
                <legend>
                    <center>
                        <strong>Produtos de Higiene</strong>
            </center>
        </h1><br> 
        </div>
        <fieldset class="grupo">
    <div class="campo">
            <strong><label for="Nome do Produto">Nome do Produto</label></strong> 
            <input type="text" id="DescricaoProd" name="DescricaoProd" required="" style="width:350px">
        </div>
    <div class="campo"> 
        <strong><label for="Unidade">Unidade</label></strong> 
            <input type="text" id="DescricaoUnid" name="DescricaoUnid" style="width:160px" required="" size="120">
        </div>
        </fieldset>
        <button class="btn btn-success btn_contact" type="button">Registo</button>
</form>
</section> 

<script type="text/javascript"> 
$(".btn_contact").click(function () {

                $.ajax({
                    type: "POST",
                    url: "./inserir",
                    data: $("#feedback_form").serialize(), // serializes the form's elements.
                    success: function (data)
                    {
                        if ($.trim(data) == 'true') {
                            $("#feedback_form").find('input').val(''); //clear text
                            $(".success_messages").removeClass('hide'); // success message
                        } else {
                            $(".error_message").removeClass('hide'); // error message
                        }
                    }
                });

            });
</script>

On the insert page I have this php code:

$name = isset($_POST["DescricaoProd"]) ? $_POST["DescricaoProd"] : '';
$unid = isset($_POST["DescricaoUnid"]) ? $_POST["DescricaoUnid"] : '';
if (!empty($name) && !empty($unid)) {  
    echo 'true';
} else {
    echo 'false';
}    

$sql = "INSERT INTO ProdHigieneteste (DescricaoProd,DescricaoUnid) 
VALUES ('$name','$unid')";
if ($conn->query($sql)) { // check for === TRUE is not necessary
   // either put the second query in here, or just enjoy the success
} else {
   // get the error, throw a message...
}
$sql1 = "INSERT INTO StockHigieneteste (DescricaoProd,DescricaoUnid) 
VALUES ('$name','$unid')";
if ($conn->query($sql1) === TRUE) {
    //Count total number of rows
    $rowCount = $query->num_rows;
} else {
    // get the error, throw a message...
}
$conn->close(); 

I was inserting in the database table and no longer inserting, but there is no error in the console either. Someone can help identify the problem?

  • 1

    To find this problem I would give one echo $sql1 just below the variable and then put this query directly in the database to check the real problem.

  • @David Alves, I tried to do what I said but I don’t get any results, I tested the queries in mysql and they are working

  • Have you made sure that the post data is getting right pro php?

  • PPDE to post here the value of variables $sql and $sql1?

  • How can I check if the post values reach php?

  • i in php page already made var_dump ($sql); and var_dump ($sql1); and also echo, but does not show the results of the variables. I also print_r ($name); print_r ($unid);

Show 1 more comment

1 answer

1


I made some changes to your code

Script - I added dataType: "json",

$(".btn_contact").click(function () {

  $.ajax({
  type: "POST",
  url: "./inserir",
  data: $("#feedback_form").serialize(), // serializes the form's elements.
  dataType: "json",
      success: function (data)
      {
         if ($.trim(data) == 'true') {
           $("#feedback_form").find('input').val(''); //clear text
           $("#success_messages").removeClass('hide'); // success message
         } else {
           $("#error_message").removeClass('hide'); // error message
         }
      }
  });

});

In HTML - to show message

<div id="success_messages" class="hide">sucessso</div>
<div id="error_message" class="hide">erro</div>

CSS

.hide {
     display: none;
}

Insert page

$name = isset($_POST["DescricaoProd"]) ? $_POST["DescricaoProd"] : '';
$unid = isset($_POST["DescricaoUnid"]) ? $_POST["DescricaoUnid"] : '';

if (!empty($name) && !empty($unid)) {  
   echo json_encode("true");
} else {
    echo json_encode("false");
}

$conn = new mysqli ("localhost", "USUARIO", "SENHA", "nome_DB");

$sql = "INSERT INTO ProdHigieneteste (DescricaoProd,DescricaoUnid) 
VALUES ('$name','$unid')";
if ($conn->query($sql)) { // check for === TRUE is not necessary
   // either put the second query in here, or just enjoy the success
} else {
   // get the error, throw a message...
}

$sql1 = "INSERT INTO StockHigieneteste (DescricaoProd,DescricaoUnid) 
VALUES ('$name','$unid')";

$query = mysqli_query($conn, "SELECT * FROM StockHigieneteste");

if ($conn->query($sql1) === TRUE) {
    //Count total number of rows
    $rowCount = $query->num_rows;
} else {
    // get the error, throw a message...
}


$conn->close();

OBS: On the insert page you forgot to make a SELECT to be able to return the total number of lines

If the above fixes still give problems, and since it is a local server, your problem may be in mysql Workbench. Restart mysql Workbench.

  • I appreciate your help, but do not insert in the table, but there is no error in the console.

  • yes insert as said but here in my web application is not inserting, but if you force an error on the page where I have php it will stop the error right away, but I can’t understand why you are not inserting.

  • What is the structure of the table?

  • CREATE TABLE ProdHigieneteste (&#xA; IDProd int(11) NOT NULL AUTO_INCREMENT,&#xA; DescricaoProd varchar(100) COLLATE utf8_unicode_ci NOT NULL,&#xA; DescricaoUnid varchar(25) COLLATE utf8_unicode_ci NOT NULL,&#xA; Ativo varchar(45) COLLATE utf8_unicode_ci DEFAULT '1',&#xA; PRIMARY KEY (IDProd)&#xA;) ENGINE=InnoDB AUTO_INCREMENT=309 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

  • but the active variable does not exist in the form, I also have to create this input in the form?

  • That’s right, you don’t, now that I’ve noticed DEFAULT '1'

  • I created the table with your CREATE TABLE and keep inserting right here

  • is that I’m having this problem by using wordpress?

  • Strange this, wordpress does not understand, but has nothing to do with PHP. Something must be going unnoticed, and worse that does not accuse error.

  • Already tested put wrong password on the connection to see if you are error?

  • I for example take a { or a ) on the Chrome console accuses the error Intern 500.

  • I don’t know what else to say, the code is right, the table is also correct, here on my server works correctly.

Show 8 more comments

Browser other questions tagged

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