What best practices should be followed when creating tables and inserting data into a MySQL database using PHP?
When creating tables and inserting data into a MySQL database using PHP, it is important to follow best practices to ensure data integrity and security. This includes properly sanitizing user input to prevent SQL injection attacks, using parameterized queries to prevent SQL injection, and validating data before inserting it into the database.
// 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']);
// Prepare and bind SQL statement
$stmt = $conn->prepare("INSERT INTO users (name, email) VALUES (?, ?)");
$stmt->bind_param("ss", $name, $email);
// Execute the statement
$stmt->execute();
// Close the connection
$stmt->close();
$conn->close();