Problem inserting in mysql table

0

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 on the menu where I have this code it inserts a blank line in the mysql table and should not because I have not even created the form.

Can anyone help?

    
asked by anonymous 28.12.2017 / 17:15

1 answer

1

To avoid inserting while there is no form to submit, place your code inside a 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 insert

<form .....>
............
............
<input type="submit" name="submit" value="submit" />
</form>
    
28.12.2017 / 17:33