How can data security be compromised when extending MySQLi in PHP and what measures can be taken to prevent it?
When extending MySQLi in PHP, data security can be compromised if user input is not properly sanitized before being used in SQL queries. To prevent this, always use prepared statements with parameterized queries to prevent SQL injection attacks. This ensures that user input is treated as data rather than executable code.
// Establish a connection to the database
$mysqli = new mysqli("localhost", "username", "password", "database");
// Prepare a SQL statement with a parameterized query
$stmt = $mysqli->prepare("SELECT * FROM users WHERE username = ?");
$stmt->bind_param("s", $username);
// Sanitize user input before binding it to the query
$username = filter_var($_POST['username'], FILTER_SANITIZE_STRING);
// Execute the query
$stmt->execute();
// Process the results
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
// Do something with the data
}
// Close the statement and connection
$stmt->close();
$mysqli->close();