php – Error inserting data into database

Question:

I'm watching php classes, and in the video the guy uses the mysql command, but I know it's old and insecure and I used mysqli , but the code doesn't show any error, but it doesn't write data in my table, follow the form page and from INSERT :

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8"/>
    <title>Comentário</title>
</head>


<body>
    <form method="post" action="#">
        <table>  
        <tr>
             <td><h1>Comente</h1></td>
        </tr>
        <tr>
            <td>Nome</td>
            <td><input type="text" name="txtNome"/></td>
        </tr>
        <tr>
            <td>Email</td>
            <td><input type="email" name="txtEmail"/></td>
        </tr>
        <tr>
            <td>Mensagem</td>
            <td><textarea name="txtMsg"></textarea></td>
        </tr>
        <tr>
            <td>Data</td>
            <td><?php echo date("Y-m-d"); ?></td>
        </tr>
        <tr>
            <td><input type="submit" value="Comentar"/></td>
            <td><input type="reset" value="Cancelar"/></td>
        </tr>
        </table>
    </form>
    <?php
    if(isset($_POST['txtNome']))
        $nome = $_POST['txtNome'];
    else
        $nome = '';
    if(isset($_POST['txtEmail']))
        $email = $_POST['txtEmail'];
    else
        $email = '';
    if(isset($_POST['txtMsg']))
        $msg = $_POST['txtMsg'];
    else
        $msg = '';
    $data = date("Y-m-d");
    $conn = mysqli_connect('localhost', 'root', '', 'aula', '3306');
    if (!$conn) {
        die('Could not connect to MySQL: ' . mysqli_connect_error());
    }
    mysqli_query($conn, 'SET NAMES \'utf8\'');
    $tableQuery = "INSERT INTO `comentario`(`id`, `nome`, `email`, `msg`, `data`) VALUES ('','$nome','$email','$msg','$data')";
    mysqli_query($conn, $tableQuery);
    mysqli_close($conn);
    ?>

</body>


</html>

And the BD script:

SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";
--
-- Database: `aula`
--

-- --------------------------------------------------------

--
-- Estrutura da tabela `comentario`
--

CREATE TABLE IF NOT EXISTS `comentario` (
  `id` varchar(10) NOT NULL,
  `nome` varchar(80) DEFAULT 'nome',
  `email` varchar(80) DEFAULT 'main@main.com',
  `msg` varchar(1000) DEFAULT 'mensagem',
  `data` date DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `id` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

What would be my mistake?

Answer:

The error says that the code inserted already exists, this is because the id column is a varchar and its uniqueness in this case depends on the system/application. To leave this responsibility to the database, change this column to int , not null and auto increment

`id` int NOT NULL AUTO_INCREMENT,
Scroll to Top