What is the best practice for inserting data from multiple form fields into a MySQL database using PHP?
When inserting data from multiple form fields into a MySQL database using PHP, it is best practice to sanitize the input data to prevent SQL injection attacks. One way to achieve this is by using prepared statements with parameterized queries. This helps to separate the data from the SQL query, making it more secure.
// Assuming form fields are submitted via POST method
$name = $_POST['name'];
$email = $_POST['email'];
$age = $_POST['age'];
// Establish a connection to the MySQL database
$pdo = new PDO("mysql:host=localhost;dbname=mydatabase", "username", "password");
// Prepare the SQL query using a prepared statement
$stmt = $pdo->prepare("INSERT INTO users (name, email, age) VALUES (:name, :email, :age)");
// Bind the parameters to the prepared statement
$stmt->bindParam(':name', $name);
$stmt->bindParam(':email', $email);
$stmt->bindParam(':age', $age);
// Execute the prepared statement
$stmt->execute();