How can beginners effectively use PHP to save and retrieve form data from a database?

To save and retrieve form data from a database using PHP, beginners can use SQL queries to insert data into the database and retrieve it later. They can establish a connection to the database, sanitize the input data to prevent SQL injection, and use prepared statements for secure database operations.

// Establish database connection
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database_name";

$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// Save form data to the database
$name = $_POST['name'];
$email = $_POST['email'];

$stmt = $conn->prepare("INSERT INTO users (name, email) VALUES (?, ?)");
$stmt->bind_param("ss", $name, $email);
$stmt->execute();

// Retrieve form data from the database
$result = $conn->query("SELECT * FROM users");
if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        echo "Name: " . $row["name"]. " - Email: " . $row["email"]. "<br>";
    }
} else {
    echo "0 results";
}

// Close database connection
$conn->close();