What are common pitfalls when using MySQLi in PHP for data retrieval and insertion?

One common pitfall when using MySQLi in PHP for data retrieval and insertion is not properly sanitizing user input, which can lead to SQL injection attacks. To prevent this, you should always use prepared statements with parameterized queries to securely interact with the database.

// Connect to the database
$mysqli = new mysqli("localhost", "username", "password", "database");

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

// Prepare a SQL statement with a parameterized query
$stmt = $mysqli->prepare("INSERT INTO table_name (column1, column2) VALUES (?, ?)");

// Bind parameters to the statement
$stmt->bind_param("ss", $value1, $value2);

// Set the parameter values
$value1 = "value1";
$value2 = "value2";

// Execute the statement
$stmt->execute();

// Close the statement and connection
$stmt->close();
$mysqli->close();