Search code examples
phphtmlsqlinsertisset

Failed insert into database


I've a problem with this code. I've this html form

<form method="post" action="invio_db1.php">
    Nome <input type="text" name="nome"> <br><br>
    Cognome <input name="cognome" type="text"> <br><br>

    <input value="Invia" type="submit">
    <input value="Reset" type="reset">
</form>

and this php code

<?php
    $host = "127.0.0.1";
    $nick = "root";
    $pw = "";
    $db_name = "associazydbe";

    $db = mysqli_connect($host, $nick, $pw) or die ("Errore nella connessione");
    mysqli_select_db($db, $db_name) or die (mysqli_error());

    if(!empty($_POST["nome"]))
        $nome = $_POST["nome"];
    else
        $nome = null;

    if(!empty($_POST['cognome']))
        $cognome = $_POST['cognome'];
    else
        $cognome = null;

    $query = "INSERT INTO persons_comeunprodigio (nome, cognome)
                  VALUES ('$nome', '$cognome')";

    mysqli_query($db, $query) or die(mysqli_error());
?>

I think it hasn't error but, after the running, in the database, all fields are null! I can't find and fix the problem.

Thanks in advance.


Solution

  • Probably you should add condition to your PHP script and insert data into database only when you send the form.

    Instead of:

       if(!empty($_POST["nome"]))
            $nome = $_POST["nome"];
        else
            $nome = null;
    
        if(!empty($_POST['cognome']))
            $cognome = $_POST['cognome'];
        else
            $cognome = null;
    
        $query = "INSERT INTO persons_comeunprodigio (nome, cognome)
                      VALUES ('$nome', '$cognome')";
    
        mysqli_query($db, $query) or die(mysqli_error());
    

    you should have:

    if (isset($_POST['nome'])) {
    
       if(!empty($_POST["nome"]))
            $nome = $_POST["nome"];
        else
            $nome = null;
    
        if(!empty($_POST['cognome']))
            $cognome = $_POST['cognome'];
        else
            $cognome = null;
    
        $query = "INSERT INTO persons_comeunprodigio (nome, cognome)
                      VALUES ('$nome', '$cognome')";
    
        mysqli_query($db, $query) or die(mysqli_error());
    }
    

    Now you need to fill in form and press submit button to insert data to database.

    However you should use at least mysqli_real_escape_string but better choice would be prepared statements. At the moment your code is vulnerable to SQL Injection.