What are common mistakes beginners make when trying to insert data into a MySQL database using PHP scripts and HTML forms?
Common mistakes beginners make when trying to insert data into a MySQL database using PHP scripts and HTML forms include not sanitizing user input, not connecting to the database properly, and not handling errors effectively. To solve these issues, always sanitize user input to prevent SQL injection attacks, establish a proper connection to the database using mysqli or PDO, and implement error handling to catch any potential issues during the data insertion process.
<?php
// Establish a connection to the MySQL database
$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);
}
// Sanitize user input
$name = mysqli_real_escape_string($conn, $_POST['name']);
$email = mysqli_real_escape_string($conn, $_POST['email']);
// Insert data into the database
$sql = "INSERT INTO users (name, email) VALUES ('$name', '$email')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
// Close the database connection
$conn->close();
?>