What are the best practices for storing survey data in a MySQL database using PHP?

When storing survey data in a MySQL database using PHP, it is important to properly sanitize user input to prevent SQL injection attacks. It is also recommended to use prepared statements to securely insert data into the database. Additionally, creating appropriate database tables with the necessary fields for storing survey responses can help organize the data efficiently.

// Establish a connection to the MySQL database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "survey_db";

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

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

// Sanitize user input
$survey_response = mysqli_real_escape_string($conn, $_POST['survey_response']);

// Prepare and execute a SQL statement to insert survey data into the database
$stmt = $conn->prepare("INSERT INTO survey_responses (response) VALUES (?)");
$stmt->bind_param("s", $survey_response);

if ($stmt->execute()) {
    echo "Survey response stored successfully";
} else {
    echo "Error storing survey response: " . $conn->error;
}

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