Problem when inserting into mysql table

Asked

Viewed 65 times

-1

Good afternoon, I have this code:

<?php 
$servername = "xxxxxxxxxxx";
$username = "xxxxxxx";
$password = "xxxxxxxx";
$dbname = "xxxxxxx";

$conn = new mysqli($servername, $username, $password, $dbname);
$conn->set_charset('utf8');

$name = $_POST['DescricaoProd'];
$unid = $_POST['DescricaoUnid'];  

$sql = "INSERT INTO ProdHigiene (DescricaoProd,DescricaoUnid) 
VALUES ('$name','$unid')";

if ($conn->query($sql) === TRUE);

//Count total number of rows
$rowCount = $query->num_rows;

$conn->close();
?> 

My problem is that whenever I open the page in the menu where I have this code it inserts a blank line in the mysql table and should not because I have not yet created the form.

Someone can help?

  • Tour the site, starting with https://pt.meta.stackoverflow.com/questions/1078/como-e-por-que-aceitar-uma-resposta/1079#1079

1 answer

1


To avoid Insert while there is no form to submit, place your code within a condition if

//isset — Informa se a variável foi iniciada
//!empty se a variável não é vazia

if (isset($_POST['submit']) && (!empty($_POST['submit']))) {
    $servername = "xxxxxxxxxxx";
    $username = "xxxxxxx";
    $password = "xxxxxxxx";
    $dbname = "xxxxxxx";

    $conn = new mysqli($servername, $username, $password, $dbname);
    $conn->set_charset('utf8');

    $name = $_POST['DescricaoProd'];
    $unid = $_POST['DescricaoUnid'];  

    $sql = "INSERT INTO ProdHigiene (DescricaoProd,DescricaoUnid) 
    VALUES ('$name','$unid')";

    if ($conn->query($sql) === TRUE);

    //Count total number of rows
    $rowCount = $query->num_rows;

    $conn->close();
}

When there is a form to be inserted

<form .....>
............
............
<input type="submit" name="submit" value="submit" />
</form>
  • thanks.... solved my problem

Browser other questions tagged

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