Pietro Ottati
Pietro Ottati

Reputation: 39

PHP7-MariaDB Insert data form

I'm a newbie so please be patient I'd like to create an HTML form that adding DATA to MariaDB. Just basic! But I'm not able to

    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 
Transitional//EN" 
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<meta charset="utf-8" />
<head>
<title>PAGINA CARICAMENTO DATI</title>
</head>

<body>
<table border="0">
  <tr>
    <td align="center">Inserisci i dati richiesti</td>
  </tr>
  <tr>
    <td>
      <table>
        <form method="post" action="input.php">
        <tr>
          <td>Nome</td>
          <td><input type="text" name="name" size="20">
          </td>
        </tr>
        <tr>
          <td>Cognome</td>
          <td><input type="text" name="surname" size="20">
          </td>
        </tr>
         <tr>
          <td>Città</td>
          <td><input type="text" name="city" size="20">
          </td>
        </tr>
        <tr>
          <td></td>
          <td align="right"><input type="submit" 
          name="submit" value="Sent"></td>
        </tr>
        </form>
        </table>
      </td>
    </tr>
</table>
</body>
</html> 

AND the PHP part is:

<?php
$host='localhost';
$user='root';
$password='password';
$database='esempio';

$connection = mysqli_connect($host,$user,$password,$database);
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}


$name = $_POST['name'];
$surname = $_POST['surname'];
$city = $_POST['city'];

printf($name);
printf($surname);
printf($city);

$sql="INSERT INTO people (ID,Name,Surname,City)VALUES(default,$name,$surname,$city)";
printf($sql);
if(!mysqli_query($connection,$sql)){ 
printf("Errore: %s\n",mysqli_error($connection));
}
mysqli_close($connection);
?>

MAriaDB have 4 columns:

  1. ID Index int(11) No None AUTO_INCREMENT Change Change Drop Drop
  2. Name tinytext utf8_general_ci No None Change Change Drop Drop
  3. Surname tinytext utf8_general_ci No None Change Change Drop Drop
  4. City tinytext utf8_general_ci No None Change Change Drop Drop

Upvotes: 1

Views: 1468

Answers (1)

Funk Forty Niner
Funk Forty Niner

Reputation: 74217

Strings values require them to be quoted.

VALUES('','$name','$surname','$city')

Note: Since your ID column is an AI, remove the default.

However, this would require you to escape your data for 2 reasons.

  • If any of those values contains characters that MySQL would complain about; i.e.: apostrophes.
  • Open to an SQL injection.

Use a prepared statement instead.

Check for errors on the query also:

And error reporting:

You should also check for empty inputs.

Another thing is to make sure you've made the right choice of column types. tinytext may not be what you want to use here, but will still work; varchar is usually the preferred choice when using string literals.

Consult:


HTML stickler:

  • <form> cannot be child of <table>.

Upvotes: 1

Related Questions