42

I am just learning about databases and I want to be able to store user inputs. What would be a basic example on how to get form data and save it to a database using PHP?

Also making the form secure from SQL attacks.

Your Common Sense
  • 156,878
  • 40
  • 214
  • 345
bammab
  • 2,543
  • 7
  • 25
  • 28

1 Answers1

33

File sample.html

<form action="sample.php" method="POST">
    <input name="name" type="text">
    <input name="text" type="text">
    <input name="submit" type="submit" value="Submit">
</form>

File sample.php

<?php

if (isset($_POST['submit'])) {
    mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
    $mysqli = new mysqli('localhost', 'user', 'password', 'mysampledb');

    // replace every piece of data in SQL with question mark 
    $sql = "INSERT INTO SampleTable (name, text) VALUES (?,?)"
    //                                  2 question marks ^^^
    // prepare this query
    $stmt = $mysqli->prepare($sql);
    // bind every variable, adding s for each to the types string
    $stmt->bind_param('ss', $_POST['name'], $_POST['text']);
    //     2 s letters ^^        ^^   2 variables   ^^

    /* Execute prepared statement */
    $stmt->execute();
}

This is a very basic example. Many PHP developers today are turning to PDO. Mysqli isn’t obsolete, but PDO is much easier, IMHO.

Your Common Sense
  • 156,878
  • 40
  • 214
  • 345
Herbert
  • 5,698
  • 2
  • 26
  • 34