What potential pitfalls can arise when inserting data into a MySQL database using PHP?
One potential pitfall when inserting data into a MySQL database using PHP is SQL injection attacks, where malicious SQL statements are inserted into input fields to manipulate the database. To prevent this, you should always use prepared statements with parameterized queries to sanitize user input and prevent SQL injection attacks.
// Establish a connection to the database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
$conn = new mysqli($servername, $username, $password, $dbname);
// Prepare a SQL statement using a parameterized query
$stmt = $conn->prepare("INSERT INTO table_name (column1, column2) VALUES (?, ?)");
$stmt->bind_param("ss", $value1, $value2);
// Set the parameter values and execute the statement
$value1 = "input_value1";
$value2 = "input_value2";
$stmt->execute();
// Close the statement and database connection
$stmt->close();
$conn->close();