40

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.

RiggsFolly
  • 89,708
  • 20
  • 100
  • 143
bammab
  • 2,473
  • 7
  • 24
  • 27

1 Answers1

32

###File sample.html

<form action="sample.php" method="POST">
    <input name="sample" 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');

    $stmt = $mysqli->prepare("INSERT INTO SampleTable VALUES (?)");
    $stmt->bind_param('s', $sample);   // Bind $sample to the parameter

    $sample = $_POST['sample'] ?? '';

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

    printf("%d Row inserted.\n", $stmt->affected_rows);
}

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

Dharman
  • 26,923
  • 21
  • 73
  • 125
Herbert
  • 5,500
  • 2
  • 24
  • 34